I'm developing an Android app, with which the user can log in and do their task. To log in, it has to connect to the server. I've searched the internet, but most of the examples are about using GET method, not POST. So after I solved my problem, I write this post for those looking for a similar solution.
1. write this in your manifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
2. server side:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name = request.getParameter("name");
PrintWriter out = response.getWriter();
out.println("Hello "+name);
}
3. Android side, instead of using the main thread, you need to execute the connection in the background. First, implement your own thread:
private class BKTask extends AsyncTask<String, Void, String> {
private String name="";
@Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
private String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = getHttpConnection(url);
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
} catch (IOException e1) {
e1.printStackTrace();
}
return output.toString();
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("POST");
httpConnection.setDoOutput(true);
httpConnection.connect();
//post
OutputStreamWriter writer = new OutputStreamWriter(httpConnection.getOutputStream());
String urlParameters = "name="+name;
writer.write(urlParameters);
writer.flush();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
writer.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
@Override
protected void onPostExecute(String output) {
msg.setText(output);
}
}
4. how to use this thread? See the following code. I use a button to submit the request, so this is my code which is called when the button is clicked:
public void submit(View v){
BKTask task = new BKTask();
task.name = name.getText().toString();
task.execute(new String[] { URL });
}
That's all. If any questions, please leave me a msg:)
Stay Hungry Stay Foolish
Thursday, 12 September 2013
Sunday, 23 December 2012
How to set weight in linearlayout in Android
Today I was writing an app on Android. There was a LinearLayout with 3 TextViews which fill the screen. I wanted their width to be 1:6:6. So I set the "android:layout_weight" property 1, 6, 6. But it didn't work that way. The first TextView became very big and the other two become very small. Then I guess the "weight" means importance. The smaller the weight is, the larger it will be. So I read a lot and found this method to set the weights of the components in your app:
1. Suppose the size of the screen is X.
2. Count how many views there are in a LinearLayout, here I use my example, 3.
3. Total width: total = 3X.
4. delta = X - total = -2X.
5. Suppose you set the weight of the first TextView to be A.
6. Suppose you want the TextView to be 1/13 of the width of the screen.
7. Then use this formula to solve the value of 'A': X + delta*(A/13) = (1/13)X , A=6
I did like this and got the three weight values: 6, 3.5, 3.5, and I got the result exactly as I wanted, the width of the three TextView is 1:6:6.
1. Suppose the size of the screen is X.
2. Count how many views there are in a LinearLayout, here I use my example, 3.
3. Total width: total = 3X.
4. delta = X - total = -2X.
5. Suppose you set the weight of the first TextView to be A.
6. Suppose you want the TextView to be 1/13 of the width of the screen.
7. Then use this formula to solve the value of 'A': X + delta*(A/13) = (1/13)X , A=6
I did like this and got the three weight values: 6, 3.5, 3.5, and I got the result exactly as I wanted, the width of the three TextView is 1:6:6.
Sunday, 9 December 2012
Simulation of Collision Detection using OpenGL
This is a project that I'm very proud of. We built up a physical world using OpenGL.
Balancing Board
The board is made up of a gridded
X-Z plane, bordered at the sides by border walls. This is the space in which
the ball can roam freely.
Material Selection
This graphical user interface is to
use to select the materials for the ball. It includes metal, wool and plastic
ball material.
Walls
There are two kinds of walls –
border walls and red walls. Border walls are used to hold the ball within the
board. The red walls shown here are strips of X-Y planes of a predefined
length. All walls are of height r, where r is the radius of the ball.
Ball
The ball can only travel in the X-Z
plane. It can be simulated with different materials.
Controls
The balancing board can be tilted in
the x-axis and z-axis by using the mouse. The angular limits in both directions
are ±45°.
Thursday, 4 October 2012
A simple mesh viewer
As a beginner of openGL, I spent several days and finished this mesh viewer using VC++. This mesh viewer can read 3D model from M file and draw the model. It also has the following functions:
1. select file;
2. set projection;
3. draw object by points/wireframe/smooth shading/flat shading;
4. draw xyz axis;
5. draw xz plane;
6. draw boundary box;
7. translate object/camera;
8. rotate object/camera;
9. scale object/camera
Here is the picture
First, let me show you the format of M file. In a M file, vertices and faces are defined:
# Created on 2012/09/12 05:06:24 using:
# filtermesh cap.m -removeinfo
# (Timing on cpu=x86 Family 6 Model 37 Stepping 2, GenuineIntel host=?)
# (_readmesh: 0.00)
# (Filtermesh: 0.00)
Vertex 1 -0.00418561 0.93191 4.22368
Vertex 2 -0.492633 1.82421 3.84173
Vertex 3 -0.884398 2.62797 3.2424
Vertex 4 4.43596 -3.0351 0.881848Face 1 1 2 3
Face 2 2 3 4
Face 3 3 4 1
Face 4 4 1 2
I stored all the information into two vectors: a vector of vertices and a vector of faces.
vector<Vertices> v;
vector<Face> f;
While reading each face, I compute the normal vector and put it into each of the three vertices of the face. At last, I normalize all the normal vectors in each vertex to generate its final normal vector.
Then I creat the main window and another glui window. I didn't creat glui subwindow on the main window, because if I do so, it would be difficult to control when I resize the main window.
Since it's a consule application, I cannot use open-file dialog. So I can only use the fileBrowser provided by glui.
I put two sets of rotation and translation controls, one is for object, the other is for camera.
After building the user interface, some callback functions have to be defined:
glutReshapeFunc function is called the first time the window is generated and every time it's resized.
glutDisplayFunc is the main part of this app. It is called many time in a second to draw objects on the window.
In glutDisplayFunc, first I set projection matrix.
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
if(projection==0){
glOrtho(-maxLength,maxLength,-maxLength,maxLength,-maxLength*2,maxLength*2);
//set camera
gluLookAt(maxLength/8,maxLength/8,maxLength/8,0,0,0,0,1,0);
}
else{
gluPerspective(60,1,maxLength/100,maxLength*4);
//set camera
gluLookAt(maxLength,maxLength,maxLength,0,0,0,0,1,0);
}
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
You have to set the current matrix to modelview after you set it to projection.
Then I compute the current matrix to rotate, translate, and zoom in/out the camera.
glMultMatrixf (cameraRotation);
glScalef(size,size,size);
glTranslatef(tx,ty,tz);
After this, draw xyz axis and xz-plane. This must be done before moving the object.
To rotate, translate, or update the size of the object, you can use the same way as the camera.
Finally, you can draw your object. Since all the object are triangle mesh, you can just draw triangles. It's very simple.
for(int i=1;i<f.size();i++){
glBegin(mode);
glNormal3fv(v[f[i].a].n);
glVertex3f(v[f[i].a].x,v[f[i].a].y,v[f[i].a].z);
glNormal3fv(v[f[i].b].n);
glVertex3f(v[f[i].b].x,v[f[i].b].y,v[f[i].b].z);
glNormal3fv(v[f[i].c].n);
glVertex3f(v[f[i].c].x,v[f[i].c].y,v[f[i].c].z);
glEnd();
}
Run this app, you can load a mesh file and do the operations on the control box.
That's all. I don't have much time to cover the details here. If you have questions, please leave a message:)
Thanks for viewing:)
1. select file;
2. set projection;
3. draw object by points/wireframe/smooth shading/flat shading;
4. draw xyz axis;
5. draw xz plane;
6. draw boundary box;
7. translate object/camera;
8. rotate object/camera;
9. scale object/camera
Here is the picture
First, let me show you the format of M file. In a M file, vertices and faces are defined:
# Created on 2012/09/12 05:06:24 using:
# filtermesh cap.m -removeinfo
# (Timing on cpu=x86 Family 6 Model 37 Stepping 2, GenuineIntel host=?)
# (_readmesh: 0.00)
# (Filtermesh: 0.00)
Vertex 1 -0.00418561 0.93191 4.22368
Vertex 2 -0.492633 1.82421 3.84173
Vertex 3 -0.884398 2.62797 3.2424
Vertex 4 4.43596 -3.0351 0.881848Face 1 1 2 3
Face 2 2 3 4
Face 3 3 4 1
Face 4 4 1 2
I stored all the information into two vectors: a vector of vertices and a vector of faces.
vector<Vertices> v;
vector<Face> f;
While reading each face, I compute the normal vector and put it into each of the three vertices of the face. At last, I normalize all the normal vectors in each vertex to generate its final normal vector.
Then I creat the main window and another glui window. I didn't creat glui subwindow on the main window, because if I do so, it would be difficult to control when I resize the main window.
Since it's a consule application, I cannot use open-file dialog. So I can only use the fileBrowser provided by glui.
I put two sets of rotation and translation controls, one is for object, the other is for camera.
After building the user interface, some callback functions have to be defined:
glutReshapeFunc function is called the first time the window is generated and every time it's resized.
glutDisplayFunc is the main part of this app. It is called many time in a second to draw objects on the window.
In glutDisplayFunc, first I set projection matrix.
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
if(projection==0){
glOrtho(-maxLength,maxLength,-maxLength,maxLength,-maxLength*2,maxLength*2);
//set camera
gluLookAt(maxLength/8,maxLength/8,maxLength/8,0,0,0,0,1,0);
}
else{
gluPerspective(60,1,maxLength/100,maxLength*4);
//set camera
gluLookAt(maxLength,maxLength,maxLength,0,0,0,0,1,0);
}
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
You have to set the current matrix to modelview after you set it to projection.
Then I compute the current matrix to rotate, translate, and zoom in/out the camera.
glMultMatrixf (cameraRotation);
glScalef(size,size,size);
glTranslatef(tx,ty,tz);
After this, draw xyz axis and xz-plane. This must be done before moving the object.
To rotate, translate, or update the size of the object, you can use the same way as the camera.
Finally, you can draw your object. Since all the object are triangle mesh, you can just draw triangles. It's very simple.
for(int i=1;i<f.size();i++){
glBegin(mode);
glNormal3fv(v[f[i].a].n);
glVertex3f(v[f[i].a].x,v[f[i].a].y,v[f[i].a].z);
glNormal3fv(v[f[i].b].n);
glVertex3f(v[f[i].b].x,v[f[i].b].y,v[f[i].b].z);
glNormal3fv(v[f[i].c].n);
glVertex3f(v[f[i].c].x,v[f[i].c].y,v[f[i].c].z);
glEnd();
}
Run this app, you can load a mesh file and do the operations on the control box.
That's all. I don't have much time to cover the details here. If you have questions, please leave a message:)
Thanks for viewing:)
Friday, 14 September 2012
Beginner of Android App Developing
I just developed my first app on android, so I'd like to share my experience.
1. Download and install the latest JDK: http://www.oracle.com/technetwork/java/javase/downloads/index.html
2. Download android SDK: http://developer.android.com/sdk/index.html , and install the packages you need.
3. Download the Eclipse: http://www.eclipse.org/downloads/ . Here you doesn't need to install it. Just open the folder and you can use it.
4. Install android plug-in to Eclipse. Open Eclipse, 'Help'->'Install New Software', input the following address: https://dl-ssl.google.com/android/eclipse/
Press 'Next' button and select all, then finish.
5. Open android AVD Manager. Create a new Android Virtual Device.
6. Turn to Eclipse, new an android project and you can run it as android application. After finishing your program, you can export your project to a APK file, then copy the file into your android device, install it, then you can play with your own app in your android.
That's all. Thanks for viewing my post.
I'm gonna write more about android app development.
1. Download and install the latest JDK: http://www.oracle.com/technetwork/java/javase/downloads/index.html
2. Download android SDK: http://developer.android.com/sdk/index.html , and install the packages you need.
3. Download the Eclipse: http://www.eclipse.org/downloads/ . Here you doesn't need to install it. Just open the folder and you can use it.
4. Install android plug-in to Eclipse. Open Eclipse, 'Help'->'Install New Software', input the following address: https://dl-ssl.google.com/android/eclipse/
Press 'Next' button and select all, then finish.
5. Open android AVD Manager. Create a new Android Virtual Device.
6. Turn to Eclipse, new an android project and you can run it as android application. After finishing your program, you can export your project to a APK file, then copy the file into your android device, install it, then you can play with your own app in your android.
That's all. Thanks for viewing my post.
I'm gonna write more about android app development.
Saturday, 18 August 2012
OpenGL beginning guide(glui)
1. Download the latest version of glui sourse code. (mine was glui-2.36)
2. Extract the zip file, and open the src/msvc/glui.sln file in vc++
3. Select the _glui library and build the library.
4. After building the library, the lib file (glui32d.lib), glui32d.lib – ‘d’ for debug, will be stored in the msvc\lib directory.
5. Put the glui32d.lib file into
6. Put the glui.h file into
7. Create new project and try to compile. That's all.
Note : For VS 2010 users, the error below may be generated when compiling the library.
Try this,
2. Extract the zip file, and open the src/msvc/glui.sln file in vc++
3. Select the _glui library and build the library.
4. After building the library, the lib file (glui32d.lib), glui32d.lib – ‘d’ for debug, will be stored in the msvc\lib directory.
5. Put the glui32d.lib file into
C:\Program Files\Microsoft Visual Studio 10.0\VC\lib
directory and rename to glui32.lib6. Put the glui.h file into
C:\Program Files\Microsoft Visual Studio 10.0\VC\include
directory.7. Create new project and try to compile. That's all.
Note : For VS 2010 users, the error below may be generated when compiling the library.
1 | error C2252: an explicit instantiation of a template can only occur at namespace scope |
Try this,
- Cut the corresponding block code and paste outside the class GLUIAPI GLUI_CommandLine definition
1
#ifdef _MSC_VER
2
// Explicit template instantiation needed for dll
3
template
class
GLUIAPI std::allocator<GLUI_String>;
4
template
class
GLUIAPI std::vector<GLUI_String,
5
std::allocator<GLUI_String> >;
6
#endif
- Put #include <iterator> after #include <cstdlib>
1
#include <cstdlib>
2
#include <iterator>
- Build it as usual
Wednesday, 8 August 2012
A Sample using GLUT
This is a sample of a moving cube:
#include <iostream>
#include <GL/glut.h>
#include <cstdlib>
using namespace std;
static GLfloat spin=0.0;
void init(void){
glClearColor(0.0,0.0,0.0,0.0);
glShadeModel(GL_FLAT);
}
void display(void){
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glRotatef(spin,0.0,0.0,1.0);
glColor3f(1.0,1.0,1.0);
glRectf(-25.0,-25.0,25.0,25.0);
glPopMatrix();
glutSwapBuffers();
}
void spinDisplay(void){
spin=spin+1.5;
if(spin>360.0)
spin=spin-360.0;
glutPostRedisplay();
}
void reshape(int w, int h){
glViewport(0,0,(GLsizei)w,(GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-50.0,50.0,-50.0,50.0,-1.0,1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void mouse(int button, int state, int x, int y){
switch(button){
case GLUT_LEFT_BUTTON:
if (state==GLUT_DOWN)
glutIdleFunc(spinDisplay);
break;
case GLUT_RIGHT_BUTTON:
if (state==GLUT_DOWN)
glutIdleFunc(NULL);
break;
default:
break;
}
}
int main(int argc, char** argv){
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(250,250);
glutInitWindowPosition(100,100);
glutCreateWindow(argv[0]);
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMouseFunc(mouse);
glutMainLoop();
return 0;
}
#include <iostream>
#include <GL/glut.h>
#include <cstdlib>
using namespace std;
static GLfloat spin=0.0;
void init(void){
glClearColor(0.0,0.0,0.0,0.0);
glShadeModel(GL_FLAT);
}
void display(void){
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glRotatef(spin,0.0,0.0,1.0);
glColor3f(1.0,1.0,1.0);
glRectf(-25.0,-25.0,25.0,25.0);
glPopMatrix();
glutSwapBuffers();
}
void spinDisplay(void){
spin=spin+1.5;
if(spin>360.0)
spin=spin-360.0;
glutPostRedisplay();
}
void reshape(int w, int h){
glViewport(0,0,(GLsizei)w,(GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-50.0,50.0,-50.0,50.0,-1.0,1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void mouse(int button, int state, int x, int y){
switch(button){
case GLUT_LEFT_BUTTON:
if (state==GLUT_DOWN)
glutIdleFunc(spinDisplay);
break;
case GLUT_RIGHT_BUTTON:
if (state==GLUT_DOWN)
glutIdleFunc(NULL);
break;
default:
break;
}
}
int main(int argc, char** argv){
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(250,250);
glutInitWindowPosition(100,100);
glutCreateWindow(argv[0]);
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMouseFunc(mouse);
glutMainLoop();
return 0;
}
Subscribe to:
Posts (Atom)