public class show extends MainScreen {
private String date1;
private long date1l;
private long date2l;
private LabelField curDate = new LabelField();
private LabelField toDate = new LabelField();
private LabelField diffe = new LabelField();
// private LabelField info;
// private LabelField empty;
// private InvokeBrowserHyperlinkField hello;
ButtonField activate = null;
ButtonField disactivate = null;
Timer timer;
Timer timer2;
public String date1s[];
int d, m, y;
int x = 1;
String day, hour, minute;
Date date = new Date();
Calendar calendar = Calendar.getInstance();;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy HH mm");
public show() {
add(curDate);
add(toDate);
add(new SeparatorField());
add(diffe);
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTick(), 0, 1000);
}
private class TimerTick extends TimerTask {
public void run() {
if (x != 0) {
date1l = date.getTime();
try {
date1 = dateFormat.format(calendar.getTime());
} catch (Exception e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("GMT+7:00"));
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.DATE, 1);
cal.set(Calendar.YEAR, 2012);
date2l = cal.getTime().getTime();
date1s = StringUtilities.stringToWords(date1);
d = Integer.parseInt(date1s[0]);
m = Integer.parseInt(date1s[1]);
y = Integer.parseInt(date1s[2]);
display();
} else {
timer.cancel();
}
}
}
public void display() {
String monw = convertToWords(m);
curDate.setText("Current Date = " + d + " " + monw + " " + y + " "
+ date1s[3] + ":" + date1s[4]);
toDate.setText("To Date = 1 February 2012 00:00");
long diffms = date2l - date1l;
long ds = diffms / 1000;
long dm = ds / 60;
long dh = dm / 60;
long dd = dh / 24;
long q = dd;
long h = (ds - (dd * 24 * 60 * 60)) / (60 * 60);
long m = (ds - (dh * 60 * 60)) / 60;
diffe.setText("Remaining Time : \n" + Long.toString(q) + " day(s) "
+ Long.toString(h) + " hour(s) " + Long.toString(m)
+ " minute(s)");
day = Long.toString(q);
hour = Long.toString(h);
minute = Long.toString(m);
showMessage();
}
/*
* private void link() { empty = new LabelField("\n\n"); add(empty); hello =
* new InvokeBrowserHyperlinkField("Click here",
* "http://indri.dedicated-it.com/wordpress/?page_id=17"); add(hello); info
* = new LabelField("\n\nPress menu then choose \"Get Link\" to access");
* add(info); }
*/
void showMessage() {
activate = new ButtonField("Activate", FIELD_HCENTER) {
protected boolean navigationClick(int action, int time) {
if (activate.isFocus()) {
Dialog.alert("Started!!");
Start();
}
return true;
}
};
add(activate);
disactivate = new ButtonField("Disactivate", FIELD_HCENTER) {
protected boolean navigationClick(int action, int time) {
if (disactivate.isFocus()) {
Dialog.alert("Stopped!!");
timer2.cancel();
}
return true;
}
};
add(disactivate);
/*
* UiEngine ui = Ui.getUiEngine(); Screen screen = new
* Dialog(Dialog.D_OK, data, Dialog.OK,
* Bitmap.getPredefinedBitmap(Bitmap.EXCLAMATION),
* Manager.VERTICAL_SCROLL); ui.queueStatus(screen, 1, true);
*/
}
public void Start() {
timer2 = new Timer();
timer2.scheduleAtFixedRate(new TimerTick2(), 0, 6000);
}
private class TimerTick2 extends TimerTask {
public void run() {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
synchronized (Application.getEventLock()) {
UiEngine ui = Ui.getUiEngine();
Screen screen = new Dialog(Dialog.D_OK, "Hello!",
Dialog.OK,
Bitmap.getPredefinedBitmap(Bitmap.EXCLAMATION),
Manager.VERTICAL_SCROLL);
ui.pushGlobalScreen(screen, 1, UiEngine.GLOBAL_QUEUE);
}
}
});
}
}
private String convertToWords(int m) {
String w = "";
switch (m) {
case 1:
w = "January";
break;
case 2:
w = "February";
break;
case 3:
w = "March";
break;
case 4:
w = "April";
break;
case 5:
w = "May";
break;
case 6:
w = "June";
break;
case 7:
w = "July";
break;
case 8:
w = "August";
break;
case 9:
w = "September";
break;
case 10:
w = "October";
break;
case 11:
w = "November";
break;
case 12:
w = "December";
break;
}
return w;
}
public boolean onClose() {
UiApplication.getUiApplication().requestBackground();
return true;
}
}
What actually is JVM 104 IllegalStateException? This program is a countdown program, which counts the remaining time from today until February 1st. Also, I implement a timer function that appears even if the application is closed. Can u please help me locate the problem? Thank you
As Richard said, you are trying to update LabelField from another thread. Try the following code snippet:
synchronized (UiApplication.getEventLock()) {
labelField.setText();
}
Try this below code and change according to your requirement;
public class FirstScreen extends MainScreen implements FieldChangeListener
{
LabelField label;
Timer timer;
TimerTask timerTask;
int secs=0;
long start,end;
String startDate="2012-01-28",endDate="2012-01-29";
ButtonField startCountDown;
public FirstScreen()
{
createGUI();
}
private void createGUI()
{
startCountDown=new ButtonField("Start");
startCountDown.setChangeListener(this);
add(startCountDown);
}
public void fieldChanged(Field field, int context)
{
if(field==startCountDown)
{
start=System.currentTimeMillis();
//this is the current time milliseconds; if you want to use two different dates
//except current date then put the comment for "start=System.currentTimeMillis();" and
//remove comments for the below two lines;
//Date date=new Date(HttpDateParser.parse(startDate));
//start=date.getTime();
Date date=new Date(HttpDateParser.parse(endDate));
end=date.getTime();
int difference=(int)(end-start);
difference=difference/1000;//Now converted to seconds;
secs=difference;
Status.show("Seconds: "+secs,100);
callTheTimer();
}
}
public void callTheTimer()
{
label=new LabelField();
add(label);
timer=new Timer();
timerTask=new TimerTask()
{
public void run()
{
synchronized (UiApplication.getEventLock())
{
if(secs!=0)
{
label.setText(""+(secs--)+" secs");
}
else
{
timer.cancel();
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
label.setText("");
Dialog.alert("Times Up");
}
});
}
}
}
};
timer.schedule(timerTask, 0, 1000);
}
protected boolean onSavePrompt()
{
return true;
}
public boolean onMenu(int instance)
{
return true;
}
public boolean onClose()
{
UiApplication.getUiApplication().requestBackground();
return super.onClose();
}
}
In this code I am taking taking two different dates and start the countdown by taking their difference(in seconds); See the comments in the code;
Related
2021-08-10 10:21:03.685 4272-4288/com.hamid.almusabaha E/libEGL: load_driver(/system/lib/egl/libGLES_emulation.so): dlopen failed: library "/system/lib/egl/libGLES_emulation.so" not found
2021-08-10 10:21:05.530 4272-4272/com.hamid.almusabaha E/ActivityThread: Failed to find provider info for com.google.android.gms.chimera
2021-08-10 10:21:06.564 4272-4343/com.hamid.almusabaha E/libEGL: validate_display:99 error 3008 (EGL_BAD_DISPLAY)
2021-08-10 10:21:06.570 4272-4332/com.hamid.almusabaha E/cr_SBApiBridge: Failed to init handler: Attempt to invoke virtual method 'java.lang.reflect.Constructor java.lang.Class.getDeclaredConstructor(java.lang.Class[])' on a null object reference
2021-08-10 10:21:11.302 4272-4272/com.hamid.almusabaha E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.hamid.almusabaha, PID: 4272
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:679)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at com.hamid.almusabaha.Musbiha_Large$7.run(Musbiha_Large.java:185)
at android.app.Activity.runOnUiThread(Activity.java:5866)
at com.hamid.almusabaha.Musbiha_Large.showFloatView(Musbiha_Large.java:179)
at com.hamid.almusabaha.MainActivity$20.onClick(MainActivity.java:318)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
This is my activity
public class Musbiha_Large {
private static boolean mIsFloatViewShowing;
private Activity mActivity;
private WindowManager mWindowManager;
private View mFloatView;
private WindowManager.LayoutParams mFloatViewLayoutParams;
private boolean mFloatViewTouchConsumedByMove = false;
private int mFloatViewLastX;
private int mFloatViewLastY;
private int mFloatViewFirstX;
private int mFloatViewFirstY;
static LinearLayout coverLargeL;
private int numpr = 0;
boolean isDark = false;
boolean isPha = false;
public
Musbiha_Large(final Activity activity) {
mActivity = activity;
LayoutInflater inflater = LayoutInflater.from(activity);
mFloatView = inflater.inflate(R.layout.musbiha_large, null);
final TextView textNbrLarge = mFloatView. findViewById ( R.id.textNbrLarge );
final ImageView PlayLarge = mFloatView. findViewById ( R.id.PlayLarge );
final ImageView lightLarge = mFloatView. findViewById ( R.id.lightLarge );
final ImageView ResetLarge = mFloatView. findViewById ( R.id.ResetLarge );
final LinearLayout lirarlightLarge = mFloatView. findViewById ( R.id.lirarlightLarge );
final ImageButton exetLarge = mFloatView.findViewById(R.id.exetLarge);
final ImageButton plph = mFloatView.findViewById(R.id.plph);
coverLargeL = mFloatView.findViewById(R.id.
coverLargeF);
exetLarge.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismissFloatView();
}
});
mFloatView.setOnClickListener(mFloatViewOnClickListener);
mFloatView.setOnTouchListener(mFloatViewOnTouchListener);
mFloatViewLayoutParams = new WindowManager.LayoutParams();
mFloatViewLayoutParams.format = PixelFormat.TRANSLUCENT;
mFloatViewLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mFloatViewLayoutParams.type = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
? WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
: WindowManager.LayoutParams.TYPE_TOAST;
mFloatViewLayoutParams.gravity = Gravity.CENTER;
mFloatViewLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
mFloatViewLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
}
public void dismissFloatView() {
if (mIsFloatViewShowing) {
mIsFloatViewShowing = false;
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (mWindowManager != null) {
mWindowManager.removeViewImmediate(mFloatView);
}
}
});
}
}
public void showFloatView() {
if (!mIsFloatViewShowing) {
mIsFloatViewShowing = true;
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (!mActivity.isFinishing()) {
mWindowManager = (WindowManager) mActivity.getSystemService(WINDOW_SERVICE);
if (mWindowManager != null) {
mWindowManager.addView(mFloatView, mFloatViewLayoutParams);
}
}
}
});
}
}
private View.OnClickListener mFloatViewOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
// Toast.makeText(mActivity, "Float view is clicked!", Toast.LENGTH_SHORT).show();
// sbha.setBackgroundResource ( R.drawable.green );
}
});
}
};
private View.OnTouchListener mFloatViewOnTouchListener = new View.OnTouchListener() {
#TargetApi(Build.VERSION_CODES.FROYO)
#Override
public boolean onTouch(View v, MotionEvent event) {
WindowManager.LayoutParams prm = mFloatViewLayoutParams;
int totalDeltaX = mFloatViewLastX - mFloatViewFirstX;
int totalDeltaY = mFloatViewLastY - mFloatViewFirstY;
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mFloatViewLastX = (int) event.getRawX();
mFloatViewLastY = (int) event.getRawY();
mFloatViewFirstX = mFloatViewLastX;
mFloatViewFirstY = mFloatViewLastY;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
int deltaX = (int) event.getRawX() - mFloatViewLastX;
int deltaY = (int) event.getRawY() - mFloatViewLastY;
mFloatViewLastX = (int) event.getRawX();
mFloatViewLastY = (int) event.getRawY();
if (Math.abs(totalDeltaX) >= 5 || Math.abs(totalDeltaY) >= 5) {
if (event.getPointerCount() == 1) {
prm.x += deltaX;
prm.y += deltaY;
mFloatViewTouchConsumedByMove = true;
if (mWindowManager != null) {
mWindowManager.updateViewLayout(mFloatView, prm);
}
} else {
mFloatViewTouchConsumedByMove = false;
}
} else {
mFloatViewTouchConsumedByMove = false;
}
break;
default:
break;
}
return mFloatViewTouchConsumedByMove;
}
};
It worked!
But when I check in my Bullet class it doesn't work and gives me an error!
This error:
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: #iterator() cannot be used nested. at
com.badlogic.gdx.utils.Array$ArrayIterator.hasNext(Array.java:577)
at com.myflappyoyun.game.states.PlayState.update(PlayState.java:53)
at com.myflappyoyun.game.states.GameStateManager.update(GameStateManager.java:25)
at com.myflappyoyun.game.FlappyDemo.render(FlappyDemo.java:36)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:225)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:126)
The process finished with exit code 0
public class PlayState extends state {
private static final int TUBE_SPACING = 125;
private static final int TUBE_COUNT = 4;
private static final int GROUND_Y_OFFSET = -50 ;
private Bird bird;
private Texture bg;
private Texture ground;
private Vector2 groundPos1 , groundPos2 ;
private Array<Tube> tubes ;
public PlayState(GameStateManager gsm) {
super(gsm);
bird= new Bird(50 , 300);
cam.setToOrtho(false, FlappyDemo.WIDTH/ 2, FlappyDemo.HEIGHT/ 2);
bg = new Texture("bg.png");
ground = new Texture("ground.png");
groundPos1 = new Vector2(cam.position.x - cam.viewportWidth / 2, GROUND_Y_OFFSET);
groundPos2 = new Vector2((cam.position.x - cam.viewportWidth / 2) + ground.getWidth(), GROUND_Y_OFFSET);
tubes = new Array<Tube>();
for (int i = 1; i < TUBE_COUNT ; i++) {
tubes.add(new Tube(i * (TUBE_SPACING + Tube.TUBE_WIDTH)));
}
}
#Override
protected void handleInput() {
if (Gdx.input.justTouched())
bird.jump();
}
#Override
public void update(float dt) {
handleInput();
updateGround();
bird.update(dt);
cam.position.x = bird.getPosition().x + 80 ;
for (Tube tube : tubes) {
if (cam.position.x - (cam.viewportWidth/ 2) > tube.getPosTopTube().x + tube.getTopTube().getWidth()){
tube.reposition(tube.getPosTopTube().x + ((Tube.TUBE_WIDTH + TUBE_SPACING) * TUBE_COUNT));
}
if (tube.collides(bird.getBounds()))
gsm.set(new PlayState(gsm));
}
if (bird.getPosition().y <= ground.getHeight() + GROUND_Y_OFFSET)
gsm.set(new PlayState(gsm));
cam.update();
}
#Override
public void render(SpriteBatch sb) {
sb.setProjectionMatrix(cam.combined);
sb.begin();
sb.draw(bg , cam.position.x - (cam.viewportWidth / 2), 0);
sb.draw(bird.getTexture(), bird.getPosition().x,bird.getPosition().y);
for (Tube tube : tubes) {
sb.draw(tube.getTopTube(), bird.getPosition().x, tube.getPosTopTube().y);
sb.draw(tube.getBottomTube(), tube.getPosBotTube().x, tube.getPosBotTube().y);
}
sb.draw(ground, groundPos1.x, groundPos1.y);
sb.draw(ground, groundPos2.x, groundPos2.y);
sb.end();
}
#Override
public void dispose() {
bg.dispose();
bird.dispose();
ground.dispose();
for (Tube tube : tubes)
tube.dispose();
System.out.println("Play State Disposed");
}
private void updateGround() {
if (cam.position.x - (cam.viewportWidth / 2) > groundPos1.x + ground.getWidth())
groundPos1.add(ground.getWidth()*2, 0);
if (cam.position.x - (cam.viewportWidth / 2) > groundPos2.x + ground.getWidth())
groundPos2.add(ground.getWidth()*2, 0);
}
}
It just looks like you should probably just change 'tubes' to the type of ArrayList, like the following:
ArrayList<Tube> tubes = new ArrayList<Tubes>();
You might be better off with a different type of collection. Check here for some ideas depending on how you ultimately use 'tubes'. Look at the implementing classes of 'List'
I need to display several tables as HTML, using JSP, coming from MySQL GROUP BY a,b,c WITH ROLLUP queries. I'm looking for a good tag library to achieve this. I have found DisplayTag, but it'was last updated in 2008. And I would prefer using the subtotals calculated by MySQL, which seems to be tricky with DisplayTag.
MySQL does subtotals by adding extra rows to the resultset with the group field set to NULL.
Is there a better alternative? Printing the table is important, paging and sorting would be nice but I can live without them. No editing of any kind.
I wrote my own quick-and-dirty tag. Note that it expects the rollup data structure returned by MySQL, haven't tested it with anything else.
Usage example:
<xxx:rollupTable cssClass="data" data="${data}">
<xxx:rollupColumn title="Person" align="left" group="true" fieldName="personName" groupFieldName="personId" tooltipLink="person"/>
<xxx:rollupColumn title="City" align="left" group="true" fieldName="cityName" groupFieldName="cityId" tooltipLink="city"/>
<xxx:rollupColumn title="Price" align="right" format="#,##0.000" fieldName="price"/>
<xxx:rollupColumn title="Amount" align="right" format="#,##0" fieldName="amount"/>
</xxx:rollupTable>
The column tag does not much but adds the column definition to the table tag for later use.
package xxx.tags;
import...
public class RollupTableColumnTag extends SimpleTagSupport {
private String title;
private boolean group = false;
private boolean sum = false;
private String fieldName; // field name to output
private String groupFieldName; // field name to test for rollup level changes
private String align;
private String format;
private String tooltipLink;
private DecimalFormat formatter;
public void doTag() throws IOException, JspTagException {
RollupTableTag parent = (RollupTableTag)findAncestorWithClass(this, RollupTableTag.class);
if (parent == null) {
throw new JspTagException("Parent tag not found.");
}
parent.addColumnDefinition(this);
}
public void setFormat(String format) {
formatter = new DecimalFormat(format);
this.format = format;
}
public DecimalFormat getFormatter() {
return formatter;
}
// other getters and setters are standard, excluded
}
The table tag does the actual hard work:
package xxx.tags;
import ...
public class RollupTableTag extends BodyTagSupport {
protected String cssClass;
protected List<Map> data;
protected List<RollupTableColumnTag> columns;
protected List<Integer> groups;
public void setCssClass(String cssClass) {
this.cssClass = cssClass;
}
public void setData(List data) {
this.data = (List<Map>)data;
}
public int doStartTag() throws JspException {
columns = new ArrayList<RollupTableColumnTag>();
groups = new ArrayList<Integer>();
return EVAL_BODY_BUFFERED;
}
public int doEndTag() throws JspException {
try {
JspWriter writer = pageContext.getOut();
if (data.size() == 0) {
writer.println("<P>No data.</P>");
return EVAL_PAGE;
}
int nLevels = groups.size();
int nNormalRowCount = 0;
boolean[] bStartGroup = new boolean[nLevels];
String[] sSummaryTitle = new String[nLevels];
for (int i=0;i<nLevels;i++) {
bStartGroup[i] = true;
}
writer.println("<TABLE class=\"" + cssClass + "\">");
writer.println("<THEAD><TR>");
for (RollupTableColumnTag column : columns) {
writer.print("<TH");
if (column.getAlign() != null) {
writer.print(" align=\"" + column.getAlign() + "\"");
}
writer.print(">" + column.getTitle() + "</TH>");
}
writer.println("</TR></THEAD>");
writer.println("<TBODY>");
for (Map dataRow : data) {
StringBuffer out = new StringBuffer();
out.append("<TR>");
// grouping columns always come first
String cellClass = null;
for (int i=0;i<nLevels-1;i++) {
if (bStartGroup[i]) {
Object dataField = dataRow.get(columns.get(groups.get(i)).getFieldName());
sSummaryTitle[i] = dataField == null ? "" : dataField.toString();
}
}
int nLevelChanges = 0;
for (int i=0;i<nLevels;i++) {
if (dataRow.get( columns.get(groups.get(i)).getGroupFieldName() ) == null) {
if (i>0) {
bStartGroup[i-1] = true;
}
nLevelChanges++;
}
}
int nTotalLevel = nLevels - nLevelChanges;
if (nLevelChanges == nLevels) { // grand total row
cellClass = "grandtotal";
addCell(out, "Grand Total:", null, cellClass, nLevelChanges);
} else if (nLevelChanges > 0) { // other total row
boolean isOneLiner = (nNormalRowCount == 1);
nNormalRowCount = 0;
if (isOneLiner) continue; // skip one-line sums
cellClass = "total"+nTotalLevel;
for (int i=0;i<nLevels-nLevelChanges-1;i++) {
addCell(out," ",null,cellClass, 1);
}
addCell(out, sSummaryTitle[nLevels-nLevelChanges-1] + " total:", null, cellClass, nLevelChanges+1);
} else { // normal row
for (int i=0;i<nLevels;i++) {
if (bStartGroup[i]) {
RollupTableColumnTag column = columns.get(groups.get(i));
Object cellData = dataRow.get(column.getFieldName());
String displayVal = cellData != null ? cellData.toString() : "[n/a]";
if (column.getTooltipLink() != null && !column.getTooltipLink().isEmpty() && cellData != null) {
String tooltip = column.getTooltipLink();
int dataid = Integer.parseInt(dataRow.get(column.getGroupFieldName()).toString());
displayVal = "<div ajaxtooltip=\"" + tooltip + "\" ajaxtooltipid=\"" + dataid + "\">" + displayVal + "</div>";
}
addCell(out, displayVal, column.getAlign(), null, 1);
} else {
addCell(out," ", null, null, 1);
}
}
for (int i=0;i<nLevels-1;i++) {
bStartGroup[i] = false;
}
nNormalRowCount++;
}
// other columns
for (RollupTableColumnTag column : columns) {
if (!column.isGroup()) {
Object content = dataRow.get(column.getFieldName());
String displayVal = "";
if (content != null) {
if (column.getFormat() != null) {
float val = Float.parseFloat(content.toString());
displayVal = column.getFormatter().format(val);
} else {
displayVal = content.toString();
}
}
addCell(out,displayVal,column.getAlign(),cellClass,1);
}
}
out.append("</TR>");
// empty row for better readability
if (groups.size() > 2 && nLevelChanges == groups.size() - 1) {
out.append("<TR><TD colspan=\"" + columns.size() + "\"> </TD>");
}
writer.println(out);
}
writer.println("</TBODY>");
writer.println("</TABLE>");
} catch (IOException e) {
e.printStackTrace();
}
return EVAL_PAGE;
}
public void addCell(StringBuffer out, String content, String align, String cssClass, int colSpan) {
out.append("<TD");
if (align != null) {
out.append(" align=\"" + align + "\"");
}
if (cssClass != null) {
out.append(" class=\"" + cssClass + "\"");
}
if (colSpan > 1) {
out.append(" colspan=\"" + colSpan + "\"");
}
out.append(">");
out.append(content);
out.append("</TD>");
}
public void addColumnDefinition(RollupTableColumnTag cd) {
columns.add(cd);
if (cd.isGroup()) groups.add(columns.size()-1);
}
}
So hi to #ll this is my fist post/question on stackoverflow :D
I need help # following :
So i integrated the Facebook SDk sucessfully in my game but i´dont get the profile picture working ...
So i tryied it oldshool on Facebooks "Tutotial" Way and followed all steps to implement login functions and so on ...
I´ve downloaded the "friendsmash_start" Sample and implemented that Stuff ...
My Main Problem is i don´t get ahead with this problem and can´t figure out what i´m doing wrong so i´m hoping for help.
Here´s the complete Code from the MainMenu Script from the sample which is the only i´ve changed ... like in the tutorial ...
Unity shows me this Error -> "The name 'LoadPicture' does not exist in the current context ... so the errors are on these two parts of code :
"LoadPicture(Util.GetPictureURL("me", 128, 128), MyPictureCallback);" in the "OnLoggedIn" function
"LoadPicture(Util.GetPictureURL("me", 128, 128), MyPictureCallback);" in the "MyPictureCallback" function
I don´t understand it cause i searched myself in the script for this function "LoadPicture" and find nothing that was ... according to the "Tutorial" of facebook here :
https://developers.facebook.com/docs/games/unity/unity-tutorial?locale=de_DE
the function should be there cause they wrote there :
"Take a look at the LoadPicture method also in MainMenu.cs to see how we use the Unity WWW class to load the image returned by the graph API."
But i can´t find it :(
HOPE SOMEONE CAN HELP ME I DON´T GET IT ...
Have that problem unfortunately very long time ... thats enoying. :(
HERE`S THE FULL CODE OF MAINMENU.CS :
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Facebook.MiniJSON;
using System;
public class MainMenu : MonoBehaviour
{
// Inspector tunable members //
public Texture ButtonTexture;
public Texture PlayTexture; // Texture for main menu button icons
public Texture BragTexture;
public Texture ChallengeTexture;
public Texture StoreTexture;
public Texture FullScreenTexture;
public Texture FullScreenActiveTexture;
public Texture ResourcesTexture;
public Vector2 CanvasSize; // size of window on canvas
public Rect LoginButtonRect; // Position of login button
public Vector2 ResourcePos; // position of resource indicators (not used yet)
public Vector2 ButtonStartPos; // position of first button in main menu
public float ButtonScale; // size of main menu buttons
public float ButtonYGap; // gap between buttons in main menu
public float ChallengeDisplayTime; // Number of seconds the request sent message is displayed for
public Vector2 ButtonLogoOffset; // Offset determining positioning of logo on buttons
public float TournamentStep; // Spacing between tournament entries
public float MouseScrollStep = 40; // Amount score table moves with each step of the mouse wheel
public PaymentDialog paymentDialog;
public GUISkin MenuSkin;
public int CoinBalance;
public int NumLives;
public int NumBombs;
public Texture[] CelebTextures;
public string [] CelebNames;
// Private members //
private static MainMenu instance;
private static List<object> friends = null;
private static Dictionary<string, string> profile = null;
private static List<object> scores = null;
private static Dictionary<string, Texture> friendImages = new Dictionary<string, Texture>();
private Vector2 scrollPosition = Vector2.zero;
private bool haveUserPicture = false;
private float tournamentLength = 0;
private int tournamentWidth = 512;
private int mainMenuLevel = 0; // Level index of main menu
private string popupMessage;
private float popupTime;
private float popupDuration;
void Awake()
{
Util.Log("Awake");
paymentDialog = ((PaymentDialog)(GetComponent("PaymentDialog")));
// allow only one instance of the Main Menu
if (instance != null && instance != this)
{
Destroy(gameObject);
return;
}
#if UNITY_WEBPLAYER
// Execute javascript in iframe to keep the player centred
string javaScript = #"
window.onresize = function() {
var unity = UnityObject2.instances[0].getUnity();
var unityDiv = document.getElementById(""unityPlayerEmbed"");
var width = window.innerWidth;
var height = window.innerHeight;
var appWidth = " + CanvasSize.x + #";
var appHeight = " + CanvasSize.y + #";
unity.style.width = appWidth + ""px"";
unity.style.height = appHeight + ""px"";
unityDiv.style.marginLeft = (width - appWidth)/2 + ""px"";
unityDiv.style.marginTop = (height - appHeight)/2 + ""px"";
unityDiv.style.marginRight = (width - appWidth)/2 + ""px"";
unityDiv.style.marginBottom = (height - appHeight)/2 + ""px"";
}
window.onresize(); // force it to resize now";
Application.ExternalCall(javaScript);
#endif
DontDestroyOnLoad(gameObject);
instance = this;
// Initialize FB SDK
FB.Init(SetInit, OnHideUnity);
}
private void SetInit()
{
Util.Log("SetInit");
enabled = true; // "enabled" is a property inherited from MonoBehaviour
if (FB.IsLoggedIn)
{
Util.Log("Already logged in");
OnLoggedIn();
}
}
private void OnHideUnity(bool isGameShown)
{
Util.Log("OnHideUnity");
if (!isGameShown)
{
// pause the game - we will need to hide
Time.timeScale = 0;
}
else
{
// start the game back up - we're getting focus again
Time.timeScale = 1;
}
}
private void QueryScores()
{
FB.API("/app/scores?fields=score,user.limit(20)", Facebook.HttpMethod.GET, ScoresCallback);
}
private int getScoreFromEntry(object obj)
{
Dictionary<string,object> entry = (Dictionary<string,object>) obj;
return Convert.ToInt32(entry["score"]);
}
void ScoresCallback(FBResult result)
{
Util.Log("ScoresCallback");
if (result.Error != null)
{
Util.LogError(result.Error);
return;
}
scores = new List<object>();
List<object> scoresList = Util.DeserializeScores(result.Text);
foreach(object score in scoresList)
{
var entry = (Dictionary<string,object>) score;
var user = (Dictionary<string,object>) entry["user"];
string userId = (string)user["id"];
if (string.Equals(userId,FB.UserId))
{
// This entry is the current player
int playerHighScore = getScoreFromEntry(entry);
Util.Log("Local players score on server is " + playerHighScore);
if (playerHighScore < GameStateManager.Score)
{
Util.Log("Locally overriding with just acquired score: " + GameStateManager.Score);
playerHighScore = GameStateManager.Score;
}
entry["score"] = playerHighScore.ToString();
GameStateManager.HighScore = playerHighScore;
}
scores.Add(entry);
if (!friendImages.ContainsKey(userId))
{
// We don't have this players image yet, request it now
LoadPictureAPI(Util.GetPictureURL(userId, 128, 128),pictureTexture =>
{
if (pictureTexture != null)
{
friendImages.Add(userId, pictureTexture);
}
});
}
}
// Now sort the entries based on score
scores.Sort(delegate(object firstObj,
object secondObj)
{
return -getScoreFromEntry(firstObj).CompareTo(getScoreFromEntry(secondObj));
}
);
}
void OnApplicationFocus( bool hasFocus )
{
Util.Log ("hasFocus " + (hasFocus ? "Y" : "N"));
}
// Convenience function to check if mouse/touch is the tournament area
private bool IsInTournamentArea (Vector2 p)
{
return p.x > Screen.width-tournamentWidth;
}
// Scroll the tournament view by some delta
private void ScrollTournament(float delta)
{
scrollPosition.y += delta;
if (scrollPosition.y > tournamentLength - Screen.height)
scrollPosition.y = tournamentLength - Screen.height;
if (scrollPosition.y < 0)
scrollPosition.y = 0;
}
// variables for keeping track of scrolling
private Vector2 mouseLastPos;
private bool mouseDragging = false;
void Update()
{
if(Input.touches.Length > 0)
{
Touch touch = Input.touches[0];
if (IsInTournamentArea (touch.position) && touch.phase == TouchPhase.Moved)
{
// dragging
ScrollTournament (touch.deltaPosition.y*3);
}
}
if (Input.GetAxis("Mouse ScrollWheel") < 0)
{
ScrollTournament (MouseScrollStep);
}
else if (Input.GetAxis("Mouse ScrollWheel") > 0)
{
ScrollTournament (-MouseScrollStep);
}
if (Input.GetMouseButton(0) && IsInTournamentArea(Input.mousePosition))
{
if (mouseDragging)
{
ScrollTournament (Input.mousePosition.y - mouseLastPos.y);
}
mouseLastPos = Input.mousePosition;
mouseDragging = true;
}
else
mouseDragging = false;
}
// Button drawing logic //
private Vector2 buttonPos; // Keeps track of where we've got to on the screen as we draw buttons
private void BeginButtons()
{
// start drawing buttons at the chosen start position
buttonPos = ButtonStartPos;
}
private bool DrawButton(string text, Texture texture)
{
// draw a single button and update our position
bool result = GUI.Button(new Rect (buttonPos.x,buttonPos.y, ButtonTexture.width * ButtonScale, ButtonTexture.height * ButtonScale),text,MenuSkin.GetStyle("menu_button"));
Util.DrawActualSizeTexture(ButtonLogoOffset*ButtonScale+buttonPos,texture,ButtonScale);
buttonPos.y += ButtonTexture.height*ButtonScale + ButtonYGap;
if (paymentDialog.DialogEnabled)
result = false;
return result;
}
void OnGUI()
{
GUI.skin = MenuSkin;
if (Application.loadedLevel != mainMenuLevel) return; // don't display anything except when in main menu
GUILayout.Box("", MenuSkin.GetStyle("panel_welcome"));
if (!FB.IsLoggedIn)
{
GUI.Label((new Rect(179, 11, 287, 160)), "Login to Facebook", MenuSkin.GetStyle("text_only"));
if (GUI.Button(LoginButtonRect, "", MenuSkin.GetStyle("button_login")))
{
FB.Login("email,publish_actions", LoginCallback);
}
}
if (FB.IsLoggedIn)
{
string panelText = "Welcome ";
panelText += (!string.IsNullOrEmpty(GameStateManager.Username)) ? string.Format("{0}!", GameStateManager.Username) : "Smasher!";
if (GameStateManager.UserTexture != null)
GUI.DrawTexture( (new Rect(8,10, 150, 150)), GameStateManager.UserTexture);
GUI.Label( (new Rect(179 , 11, 287, 160)), panelText, MenuSkin.GetStyle("text_only"));
}
string subTitle = "Let's smash some friends!";
if (GameStateManager.Score > 0)
{
subTitle = "Score: " + GameStateManager.Score.ToString();
}
if (!string.IsNullOrEmpty(subTitle))
{
GUI.Label( (new Rect(132, 28, 400, 160)), subTitle, MenuSkin.GetStyle("sub_title"));
}
BeginButtons();
if (DrawButton("Play",PlayTexture))
{
onPlayClicked();
}
if (FB.IsLoggedIn)
{
// Draw resources bar
Util.DrawActualSizeTexture(ResourcePos,ResourcesTexture);
Util.DrawSimpleText(ResourcePos + new Vector2(47,5) ,MenuSkin.GetStyle("resources_text"),string.Format("{0}",CoinBalance));
Util.DrawSimpleText(ResourcePos + new Vector2(137,5) ,MenuSkin.GetStyle("resources_text"),string.Format("{0}",NumBombs));
Util.DrawSimpleText(ResourcePos + new Vector2(227,5) ,MenuSkin.GetStyle("resources_text"),string.Format("{0}",NumLives));
}
#if UNITY_WEBPLAYER
if (Screen.fullScreen)
{
if (DrawButton("Full Screen",FullScreenActiveTexture))
SetFullscreenMode(false);
}
else
{
if (DrawButton("Full Screen",FullScreenTexture))
SetFullscreenMode(true);
}
#endif
DrawPopupMessage();
}
public void AddPopupMessage(string message, float duration)
{
popupMessage = message;
popupTime = Time.realtimeSinceStartup;
popupDuration = duration;
}
public void DrawPopupMessage()
{
if (popupTime != 0 && popupTime + popupDuration > Time.realtimeSinceStartup)
{
// Show message that we sent a request
Rect PopupRect = new Rect();
PopupRect.width = 800;
PopupRect.height = 100;
PopupRect.x = Screen.width / 2 - PopupRect.width / 2;
PopupRect.y = Screen.height / 2 - PopupRect.height / 2;
GUI.Box(PopupRect,"",MenuSkin.GetStyle("box"));
GUI.Label(PopupRect, popupMessage, MenuSkin.GetStyle("centred_text"));
}
}
void TournamentGui()
{
GUILayout.BeginArea(new Rect((Screen.width - 450),0,450,Screen.height));
// Title box
GUI.Box (new Rect(0, - scrollPosition.y, 100,200), "", MenuSkin.GetStyle("tournament_bar"));
GUI.Label (new Rect(121 , - scrollPosition.y, 100,200), "Tournament", MenuSkin.GetStyle("heading"));
Rect boxRect = new Rect();
if(scores != null)
{
var x = 0;
foreach(object scoreEntry in scores)
{
Dictionary<string,object> entry = (Dictionary<string,object>) scoreEntry;
Dictionary<string,object> user = (Dictionary<string,object>) entry["user"];
string name = ((string) user["name"]).Split(new char[]{' '})[0] + "\n";
string score = "Smashed: " + entry["score"];
boxRect = new Rect(0, 121+(TournamentStep*x)-scrollPosition.y , 100,128);
// Background box
GUI.Box(boxRect,"",MenuSkin.GetStyle("tournament_entry"));
// Text
GUI.Label (new Rect(24, 136 + (TournamentStep * x) - scrollPosition.y, 100,128), (x+1)+".", MenuSkin.GetStyle("tournament_position")); // Rank e.g. "1.""
GUI.Label (new Rect(250,145 + (TournamentStep * x) - scrollPosition.y, 300,100), name, MenuSkin.GetStyle("tournament_name")); // name
GUI.Label (new Rect(250,193 + (TournamentStep * x) - scrollPosition.y, 300,50), score, MenuSkin.GetStyle("tournament_score")); // score
Texture picture;
if (friendImages.TryGetValue((string) user["id"], out picture))
{
GUI.DrawTexture(new Rect(118,128+(TournamentStep*x)-scrollPosition.y,115,115), picture); // Profile picture
}
x++;
}
}
else GUI.Label (new Rect(180,270,512,200), "Loading...", MenuSkin.GetStyle("text_only"));
// Record length so we know how far we can scroll to
tournamentLength = boxRect.y + boxRect.height + scrollPosition.y;
GUILayout.EndArea();
}
// React to menu buttons //
private void onPlayClicked()
{
Util.Log("onPlayClicked");
if (friends != null && friends.Count > 0)
{
// Select a random friend and get their picture
Dictionary<string, string> friend = Util.RandomFriend(friends);
GameStateManager.FriendName = friend["first_name"];
GameStateManager.FriendID = friend["id"];
GameStateManager.CelebFriend = -1;
LoadPictureURL(friend["image_url"],FriendPictureCallback);
}
else
{
//We can't access friends
GameStateManager.CelebFriend = UnityEngine.Random.Range(0,CelebTextures.Length - 1);
GameStateManager.FriendName = CelebNames[GameStateManager.CelebFriend];
}
// Start the main game
Application.LoadLevel("GameStage");
GameStateManager.Instance.StartGame();
}
public void SetFullscreenMode (bool on)
{
if (on)
{
Screen.SetResolution (Screen.currentResolution.width, Screen.currentResolution.height, true);
}
else
{
Screen.SetResolution ((int)CanvasSize.x, (int)CanvasSize.y, false);
}
}
public static void FriendPictureCallback(Texture texture)
{
GameStateManager.FriendTexture = texture;
}
delegate void LoadPictureCallback (Texture texture);
IEnumerator LoadPictureEnumerator(string url, LoadPictureCallback callback)
{
WWW www = new WWW(url);
yield return www;
callback(www.texture);
}
void LoadPictureAPI (string url, LoadPictureCallback callback)
{
FB.API(url,Facebook.HttpMethod.GET,result =>
{
if (result.Error != null)
{
Util.LogError(result.Error);
return;
}
var imageUrl = Util.DeserializePictureURLString(result.Text);
StartCoroutine(LoadPictureEnumerator(imageUrl,callback));
});
}
void LoadPictureURL (string url, LoadPictureCallback callback)
{
StartCoroutine(LoadPictureEnumerator(url,callback));
}
void LoginCallback(FBResult result)
{
Util.Log("LoginCallback");
if (FB.IsLoggedIn)
{
OnLoggedIn();
}
}
void OnLoggedIn()
{
Util.Log("Logged in. ID: " + FB.UserId);
// Reqest player info and profile picture
FB.API("/me?fields=id,first_name,friends.limit(100).fields(first_name,id)", Facebook.HttpMethod.GET, APICallback);
LoadPicture(Util.GetPictureURL("me", 128, 128), MyPictureCallback);
}
void APICallback(FBResult result)
{
Util.Log("APICallback");
if (result.Error != null)
{
Util.LogError(result.Error);
// Let's just try again
FB.API("/me?fields=id,first_name,friends.limit(100).fields(first_name,id)", Facebook.HttpMethod.GET, APICallback);
return;
}
profile = Util.DeserializeJSONProfile(result.Text);
GameStateManager.Username = profile["first_name"];
friends = Util.DeserializeJSONFriends(result.Text);
}
void MyPictureCallback(Texture texture)
{
Util.Log("MyPictureCallback");
if (texture == null)
{
// Let's just try again
LoadPicture(Util.GetPictureURL("me", 128, 128), MyPictureCallback);
return;`
}
GameStateManager.UserTexture = texture;
}
}
change the word "LoadPicture" for "LoadPictureAPI".
For reference see:
https://github.com/fbsamples/friendsmash-unity/blob/master/friendsmash_payments_start/Assets/Scripts/MainMenu.cs
I'm doing app Google Map android.
I want draw a short path betweent 2 point in map.
But I don't know How do i need?
Please help me .Thank you very much.
new class util.java
public class Util {
private DataBaseHelper dbHelper;
private GeoFencApplicationDataset Dataset;
private int getId;
public static boolean checkConnection(Context mContext) {
NetworkInfo info = ((ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
return true;
}
return true;
}
public void DrawPath(Context c, GeoPoint src, GeoPoint dest, int color,
MapView mMapView01) {
Dataset = (GeoFencApplicationDataset) c.getApplicationContext();
dbHelper = Dataset.getDbHelper();
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");// from
urlString.append(Double.toString((double) src.getLatitudeE6() / 1.0E6));
urlString.append(",");
urlString
.append(Double.toString((double) src.getLongitudeE6() / 1.0E6));
urlString.append("&daddr=");// to
urlString
.append(Double.toString((double) dest.getLatitudeE6() / 1.0E6));
urlString.append(",");
urlString
.append(Double.toString((double) dest.getLongitudeE6() / 1.0E6));
urlString.append("&ie=UTF8&0&om=0&output=kml");
Log.d("xxx", "URL=" + urlString.toString());
Document doc = null;
HttpURLConnection urlConnection = null;
URL url = null;
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
if (doc.getElementsByTagName("GeometryCollection").getLength() > 0) {
final String path = doc.getElementsByTagName("GeometryCollection")
.item(0).getFirstChild().getFirstChild()
.getFirstChild().getNodeValue();
final String[] pairs = path.split(" ");
String[] lngLat = pairs[0].split(",");
final GeoPoint startGP = new GeoPoint(
(int) (Double.parseDouble(lngLat[1]) * 1E6),
(int) (Double.parseDouble(lngLat[0]) * 1E6));
mMapView01.getOverlays().add(
new PathOverLay(startGP, startGP, 1));
GeoPoint gp1;
GeoPoint gp2 = startGP;
for (int i = 1; i < pairs.length; i++) {
lngLat = pairs[i].split(",");
gp1 = gp2;
gp2 = new GeoPoint(
(int) (Double.parseDouble(lngLat[1]) * 1E6),
(int) (Double.parseDouble(lngLat[0]) * 1E6));
mMapView01.getOverlays().add(
new PathOverLay(gp1, gp2, 2, color));
if (getId != 0) {
dbHelper.insertTempLatLong(lngLat[1], lngLat[0], getId);
}
Log.d("xxx", "pair:" + pairs[i]);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
public double[] getLocation(Context c) {
Criteria criteria;
String provider;
LocationManager locManager = (LocationManager) c
.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
provider = locManager.getBestProvider(criteria, true);
double[] loca = new double[2];
// For Latitude & Longitude
Location location = locManager.getLastKnownLocation(provider);
if (location != null) {
loca[0] = location.getLatitude();
loca[1] = location.getLongitude();
} else {
loca[0] = 0.0;
loca[1] = 0.0;
}
return loca;
}
public void setId(int id) {
// TODO Auto-generated method stub
getId = id;
}
}
new class PathOverLay.java
public class PathOverLay extends Overlay {
private GeoPoint gp1;
private GeoPoint gp2;
private int mRadius = 6;
private int mode = 0;
private int defaultColor;
private String text = "";
private Bitmap img = null;
public PathOverLay(GeoPoint gp1, GeoPoint gp2, int mode) // GeoPoint is a
// int. (6E)
{
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
defaultColor = 999; // no defaultColor
}
public PathOverLay(GeoPoint gp1, GeoPoint gp2, int mode, int defaultColor) {
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
this.defaultColor = defaultColor;
}
public void setText(String t) {
this.text = t;
}
public void setBitmap(Bitmap bitmap) {
this.img = bitmap;
}
public int getMode() {
return mode;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
Projection projection = mapView.getProjection();
if (shadow == false) {
Paint paint = new Paint();
paint.setAntiAlias(true);
Point point = new Point();
projection.toPixels(gp1, point);
// mode=1:start
if (mode == 1) {
if (defaultColor == 999)
paint.setColor(Color.BLUE);
else
paint.setColor(defaultColor);
// RectF oval = new RectF(point.x - mRadius, point.y - mRadius,
// point.x + mRadius, point.y + mRadius);
RectF oval = new RectF(point.x - mRadius, point.y - mRadius,
point.x + mRadius, point.y + mRadius);
// start point
canvas.drawOval(oval, paint);
}
// mode=2:path
else if (mode == 2) {
if (defaultColor == 999)
paint.setColor(Color.RED);
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(5);
paint.setAlpha(70);
canvas.drawLine(point.x, point.y, point2.x, point2.y, paint);
}
/* mode=3:end */
else if (mode == 3) {
/* the last path */
if (defaultColor == 999)
paint.setColor(Color.GREEN);
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(5);
paint.setAlpha(120);
canvas.drawLine(point.x, point.y, point2.x, point2.y, paint);
RectF oval = new RectF(point2.x - mRadius, point2.y - mRadius,
point2.x + mRadius, point2.y + mRadius);
/* end point */
paint.setAlpha(120);
canvas.drawOval(oval, paint);
}
}
return super.draw(canvas, mapView, shadow, when);
}
// Read more:
// http://csie-tw.blogspot.com/2009/06/android-driving-direction-route-path.html#ixzz1hte9kGoi
}
final call method ...
util = new Util();
mapOverlays = mapView.getOverlays();
util = new Util();
util.setId(id);
GeoPoint srcGeoPoint = new GeoPoint((int) (destLat * 1E6),
(int) (destLong * 1E6));
GeoPoint destGeoPoint = new GeoPoint((int) (srcLat * 1E6),
(int) (srcLong * 1E6));
progrDialog = ProgressDialog.show(AddFenceActivity.this,
"", "Please Wait..", true);
mapView.getOverlays().add(
new PathOverLay(srcGeoPoint,destGeoPoint, 2,Color.RED));
util.DrawPath(AddFenceActivity.this, srcGeoPoint,
destGeoPoint, Color.RED, mapView);
mapView.getController().animateTo(srcGeoPoint);
public class MapOverLayItem extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
Context mContext;
public MapOverLayItem(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return mOverlays.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
return mOverlays.size();
}
public MapOverLayItem(Drawable defaultMarker, Context context) {
super(defaultMarker);
mContext = context;
}
}