my code stock.com

Here is a background task that helps me to send data(values) to my SQL Base.

Example: This is the function that will send a "value" everytime my GravitySensor is above a range.
(When I hold the phone in my hand, GravitySensor will give a value between 9 - 11. When I choose to shake the phone   a little bit, the value will change to eg. 13. , so this function,  doInBackground()  will estabilish a conection with my database.)

Snippet options

Download: Download snippet as backgroundtaskjava.java.
Copy snippet: For this you need a free my code stock.com account.
Embed code : You will find the embed code for this snippet at the end of the page, if you want to embed it into a website or a blog!

package com.example.bluwif;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
public class BackgroundTask extends AsyncTask<String,Void, String> {

	Context ctx;
	BackgroundTask(Context ctx)
	{
		this.ctx = ctx;
		
	}
	
	
	@Override
	protected String doInBackground(String... params) {
		String reg_url = "http://daniandroid.server07.com/register.php";
		String method = params[0];
		if(method.equals("register"))
		{
			String name = params[1];
			try{
				URL url  = new URL(reg_url);
				HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
				httpURLConnection.setRequestMethod("POST");
				httpURLConnection.setDoOutput(true);
				OutputStream OS = httpURLConnection.getOutputStream();
				BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
				String data = URLEncoder.encode("username", "UTF-8")+ "="+ URLEncoder.encode(name,"UTF-8");
				bufferedWriter.write(data);
				bufferedWriter.flush();
				bufferedWriter.close();
				OS.close();
				InputStream IS = httpURLConnection.getInputStream();
				IS.close();
				
				return "Registration Succes...";
				
			}catch(MalformedURLException e)
			{
				e.printStackTrace();
			}catch(IOException e)
			{
				e.printStackTrace();
			}
		}
		return "Nothing";
	}
	
	protected void onPostExecute(String result)
	{
		//Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
	}




}

Create a free my code stock.com account now.

my code stok.com is a free service, which allows you to save and manage code snippes of any kind and programming language. We provide many advantages for your daily work with code-snippets, also for your teamwork. Give it a try!

Find out more and register now

You can customize the height of iFrame-Codes as needed! You can find more infos in our API Reference for iframe Embeds.