Java tutorial
package com.lucapernini.misapp; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.app.Activity; import android.app.ActionBar; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Fragment; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.res.AssetManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.SystemClock; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.Toast; import android.os.Build; import android.preference.PreferenceManager; public class Registration extends Activity { static String TAG = "Misapp Info"; EditText usernameET; EditText nomeET; EditText cognomeET; EditText emailET; CheckBox checkLicense; Button OK; Builder alert; String textL; String pageResult = ""; boolean usernameOccupated = false; String username = ""; String nome = ""; String cognome = ""; String email = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registration); final ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); alert = new AlertDialog.Builder(this); usernameET = (EditText) findViewById(R.id.editUsername); nomeET = (EditText) findViewById(R.id.editNome); cognomeET = (EditText) findViewById(R.id.editCognome); emailET = (EditText) findViewById(R.id.editEmail); checkLicense = (CheckBox) findViewById(R.id.checklicense); OK = (Button) findViewById(R.id.buttonOK); OK.setEnabled(false); checkLicense.setClickable(false); checkLicense.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { OK.setEnabled(true); } else { OK.setEnabled(false); } } }); OK.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub username = usernameET.getText().toString(); nome = nomeET.getText().toString(); cognome = cognomeET.getText().toString(); email = emailET.getText().toString(); if (!username.isEmpty() && !nome.isEmpty() && !cognome.isEmpty() && !email.isEmpty() && email.contains("@")) { sendPostRequestRegistrationStep1(username, nome, cognome, email); } else { showToast("Controlla i campi inseriti! Non lasciarli vuoti, ed inserisci la mail corretta"); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.registration, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); // if (id == R.id.action_settings) { // return true; // } if (id == android.R.id.home) { showToast("Operazione di registrazione annullata"); Intent myIntent = new Intent(getApplicationContext(), MainActivity.class); startActivityForResult(myIntent, 0); finish(); return true; } return super.onOptionsItemSelected(item); } public void showToast(String msg) { Log.i(TAG, "Misa Registration, showToast: " + msg); Toast toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, toast.getXOffset() / 2, toast.getYOffset() / 2); toast.show(); } public void getLicense() { class GetLicenseBackground extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { // TODO Auto-generated method stub InputStream is; String text = ""; AssetManager am = getAssets(); try { is = am.open("licenzaduso.txt"); InputStreamReader inputStreamReader = new InputStreamReader(is, "ISO-8859-1"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder stringBuilder = new StringBuilder(); String bufferedStrChunk = null; while ((bufferedStrChunk = bufferedReader.readLine()) != null) { stringBuilder.append(bufferedStrChunk); stringBuilder.append("\n"); } text = stringBuilder.toString(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } textL = text; alert.setTitle("Licenza d'uso"); alert.setMessage(textL); alert.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { checkLicense.setClickable(true); dialog.dismiss(); } }); return text; } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); alert.show(); } } GetLicenseBackground getLicenceBackground = new GetLicenseBackground(); getLicenceBackground.execute(); } public void viewLicense(View v) { // AssetManager am = this.getAssets(); getLicense(); // InputStream is; // String text=""; // // // // try { // is = am.open("licenzaduso.txt"); // InputStreamReader inputStreamReader = new InputStreamReader(is,"ISO-8859-1"); // BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // StringBuilder stringBuilder = new StringBuilder(); // String bufferedStrChunk = null; // while((bufferedStrChunk = bufferedReader.readLine()) != null){ // stringBuilder.append(bufferedStrChunk); // stringBuilder.append("\n"); // } // text=stringBuilder.toString(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // Builder alert = new AlertDialog.Builder(this); // alert.setTitle("Licenza d'uso"); // alert.setMessage(textL); // alert.setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, // int which) { // checkLicense.setClickable(true); // dialog.dismiss(); // } // }); // alert.show(); } private void sendPostRequestRegistrationStep1(String username, String name, String surname, String email) { class SendPostReqReg1AsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String paramUsername = params[0]; String paramName = params[1]; String paramSurname = params[2]; String paramEmail = params[3]; Log.i(TAG, "Misa Registration: sendPostRequestRegistrationStep1, doInBackground. "); HttpClient httpClient = new DefaultHttpClient(); // In a POST request, we don't pass the values in the URL. //Therefore we use only the web page URL as the parameter of the HttpPost argument HttpPost httpPost1 = new HttpPost("http://84.38.48.145/sol/registrazioneVerifica.php?lang=it"); HttpPost httpPost2 = new HttpPost("http://84.38.48.145/sol/RegistrazioneCode.php?lang=it"); // Because we are not passing values over the URL, we should have a mechanism to pass the values that can be //uniquely separate by the other end. //To achieve that we use BasicNameValuePair //Things we need to pass with the POST request BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("username", paramUsername); BasicNameValuePair nameBasicNameValuePair = new BasicNameValuePair("nome", paramName); BasicNameValuePair surnameBasicNameValuePair = new BasicNameValuePair("cognome", paramSurname); BasicNameValuePair enteorgBasicNameValuePair = new BasicNameValuePair("enteorg", ""); BasicNameValuePair emailBasicNameValuePair = new BasicNameValuePair("email", paramEmail); BasicNameValuePair telBasicNameValuePair = new BasicNameValuePair("tel", ""); BasicNameValuePair usernameDefBasicNameValuePair = new BasicNameValuePair("usernameDEF", paramUsername); BasicNameValuePair nameDefBasicNameValuePair = new BasicNameValuePair("nomeDEF", paramName); BasicNameValuePair surnameDefBasicNameValuePair = new BasicNameValuePair("cognomeDEF", paramSurname); BasicNameValuePair enteorgDefBasicNameValuePair = new BasicNameValuePair("enteorgDEF", ""); BasicNameValuePair emailDefBasicNameValuePair = new BasicNameValuePair("emailDEF", paramEmail); BasicNameValuePair telDefBasicNameValuePair = new BasicNameValuePair("telDEF", ""); BasicNameValuePair saveBasicNameValuePair = new BasicNameValuePair("salvaUsername", "termina+registrazione"); // We add the content that we want to pass with the POST request to as name-value pairs //Now we put those sending details to an ArrayList with type safe of NameValuePair List<NameValuePair> nameValuePairList1 = new ArrayList<NameValuePair>(); nameValuePairList1.add(usernameBasicNameValuePair); nameValuePairList1.add(nameBasicNameValuePair); nameValuePairList1.add(surnameBasicNameValuePair); nameValuePairList1.add(enteorgBasicNameValuePair); nameValuePairList1.add(emailBasicNameValuePair); nameValuePairList1.add(telBasicNameValuePair); List<NameValuePair> nameValuePairList2 = new ArrayList<NameValuePair>(); nameValuePairList2.add(usernameDefBasicNameValuePair); nameValuePairList2.add(nameDefBasicNameValuePair); nameValuePairList2.add(surnameDefBasicNameValuePair); nameValuePairList2.add(enteorgDefBasicNameValuePair); nameValuePairList2.add(emailDefBasicNameValuePair); nameValuePairList2.add(telDefBasicNameValuePair); nameValuePairList2.add(saveBasicNameValuePair); try { // UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs. //This is typically useful while sending an HTTP POST request. UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList1); // setEntity() hands the entity (here it is urlEncodedFormEntity) to the request. //httpPost.setHeader("Content-Type: application/x-www-form-urlencoded"); httpPost1.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); // Add your data httpPost1.setEntity(urlEncodedFormEntity); try { // HttpResponse is an interface just like HttpPost. //Therefore we can't initialize them HttpResponse httpResponse = httpClient.execute(httpPost1); // According to the JAVA API, InputStream constructor do nothing. //So we can't initialize InputStream although it is not an interface InputStream inputStream = httpResponse.getEntity().getContent(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder stringBuilder = new StringBuilder(); String bufferedStrChunk = null; while ((bufferedStrChunk = bufferedReader.readLine()) != null) { stringBuilder.append(bufferedStrChunk); } String returned = stringBuilder.toString(); Log.i(TAG, "MisaService, sendPostRequestLogin, doInBackground, returned: " + returned); return stringBuilder.toString(); } catch (ClientProtocolException cpe) { Log.i(TAG, "First Exception caz of HttpResponese :" + cpe); cpe.printStackTrace(); } catch (IOException ioe) { Log.i(TAG, "Second Exception caz of HttpResponse :" + ioe); ioe.printStackTrace(); } } catch (UnsupportedEncodingException uee) { Log.i(TAG, "An Exception given because of UrlEncodedFormEntity argument :" + uee); uee.printStackTrace(); } try { // UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs. //This is typically useful while sending an HTTP POST request. UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList2); // setEntity() hands the entity (here it is urlEncodedFormEntity) to the request. //httpPost.setHeader("Content-Type: application/x-www-form-urlencoded"); httpPost2.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); // Add your data httpPost2.setEntity(urlEncodedFormEntity); try { // HttpResponse is an interface just like HttpPost. //Therefore we can't initialize them HttpResponse httpResponse = httpClient.execute(httpPost2); // According to the JAVA API, InputStream constructor do nothing. //So we can't initialize InputStream although it is not an interface InputStream inputStream = httpResponse.getEntity().getContent(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder stringBuilder = new StringBuilder(); String bufferedStrChunk = null; while ((bufferedStrChunk = bufferedReader.readLine()) != null) { stringBuilder.append(bufferedStrChunk); } String returned = stringBuilder.toString(); Log.i(TAG, "Misa Registratopm, sendPostRequestRegistrationStep1, doInBackground, returned: " + returned); pageResult = returned; return stringBuilder.toString(); } catch (ClientProtocolException cpe) { Log.i(TAG, "First Exception caz of HttpResponese :" + cpe); cpe.printStackTrace(); } catch (IOException ioe) { Log.i(TAG, "Second Exception caz of HttpResponse :" + ioe); ioe.printStackTrace(); } } catch (UnsupportedEncodingException uee) { Log.i(TAG, "An Exception given because of UrlEncodedFormEntity argument :" + uee); uee.printStackTrace(); } return null; } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); showToast("Tentativo Registrazione in corso..."); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); elaborateRequest(result); } } SendPostReqReg1AsyncTask sendPostReqReg1AsyncTask = new SendPostReqReg1AsyncTask(); sendPostReqReg1AsyncTask.execute(username, name, surname, email); } @Override public void onBackPressed() { // TODO Auto-generated method stub super.onBackPressed(); Intent myIntent = new Intent(getApplicationContext(), MainActivity.class); startActivityForResult(myIntent, 0); finish(); } public void elaborateRequest(String result) { String compare = "Attenzione: USERNAME gi in uso"; String compare2 = "Registrazione terminata con successo"; Log.i(TAG, "Misa Registration, elaborateRequest, " + pageResult); if (result.contains(compare)) { showToast("Username gi occupato; inserirne uno nuovo e ripetere la registrazione"); } else if (result.contains(compare2)) { saveUser(); Intent myIntent = new Intent(getApplicationContext(), RegistrationOk.class); startActivityForResult(myIntent, 0); finish(); } else { showToast("Per favore riprova inserendo dati validi"); } } private void saveUser() { Log.i(TAG, "Misa Registration, saveUser"); SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); Editor editor = mySharedPreferences.edit(); editor.putString("key_login_usr", username); editor.commit(); } }