lunedì 30 settembre 2013

Insert e select data da php con JSON in Android

Con poche righe di codice, da un'app Android è possibile catture dai dati da una pagina php (che punta magari su di un database) oppure postarli e inserirli in un database da una php.
In questo esempio è utilizzato l'oggetto JSON.

Richiesta di dati ad una JSP:
public ArrayList<Map<String,String>> selectNameSurname(){
	ArrayList<Map<String,String>> listaDb = new ArrayList<Map<String,String>>();
	
	InputStream is = null;
	StringBuilder sb=null;
	String result=null;
	try{   
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost("http://wwwwww/data.php");//link
		HttpResponse response = httpclient.execute(httppost);
		HttpEntity entity = response.getEntity();
		is = entity.getContent();
		
		
	}catch(Exception e){       
		//something here
	}
	
  //convert response to string
	try{
		BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
		sb = new StringBuilder();
		sb.append(reader.readLine() + "\n");
		String line="0";
	  
		while ((line = reader.readLine()) != null) {
			sb.append(line + "\n");
		}
		 
		is.close();
		result=sb.toString();
		 
	}catch(Exception e){
		//something here
	}
	
	String name;
	String surname;
	JSONArray jArray;
	
	try{
		jArray = new JSONArray(result);
		JSONObject json_data=null;
		int j=0;
		for(int i=0;i<jArray.length();i++){
			Map<String,String> dataDb = new HashMap<String,String>();
				json_data = jArray.getJSONObject(i);
				
				name=json_data.getString("name");
				surname=json_data.getString("surname");
				++j;
				dataDb.put(POSITION, ""+j);
				dataDb.put(ONLINE_NAME, name);
				dataDb.put(ONLINE_SCORE, surname);

				listaDb.add(dataDb);
		}
	}catch(JSONException e1){
	   
	}catch (ParseException e1){
	  
	}
	return listaDb;
}

Codice nella jsp:
	
$SQL ="SELECT name, surname FROM t_player";
$result = mysql_query($SQL);



while ( $db_field = mysql_fetch_assoc($result) ) {
	$output[]=$db_field;
}
print(json_encode($output));


Post e inserimento dati:
public void insertPlayer(Player player){
	InputStream is = null;
   
	try{   
		HttpClient httpclient = new DefaultHttpClient();
		ArrayList<namevaluepair> nameValuePairs = new ArrayList<namevaluepair>(7);
		nameValuePairs.add(new BasicNameValuePair("name",player.getName()));
		nameValuePairs.add(new BasicNameValuePair("surname",player.getSurname()));

		HttpPost httppost = new HttpPost("http://wwwwww/insert.php"); //link
		httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		HttpResponse response = httpclient.execute(httppost);
		HttpEntity entity = response.getEntity();
		is = entity.getContent();
		String responseBody =convertStreamToString(is);
		
	}catch(Exception e){       
	}
}

Codice nella jsp:
$SQL = "insert into t_player ( name_player, surname_player) values ('".$_POST['name']."','".$_POST['surname']."')";	

venerdì 27 settembre 2013

Quiz v. 1.9.6

Aggiornamento per Quiz, la mia app su Android.
Nella classifica online è possibile visualizzare i punteggi di ogni giocatore per ogni categoria dei 3 quiz (italiano, spagnolo, inglese) cliccando sul nome del giocatore.
Questo è possibile solamente se il giocatore ha selezionato l'autorizzazione nella schermata delle preferenze. In questo modo oltre ad inviare il punteggio totale, invierà anche tutti gli altri punteggi.
Di seguito una schermata di esempio:

mercoledì 18 settembre 2013

Testo tutto maiuscolo o solo le iniziali e contare caratteri in Visual Basic 6

Con queste poche righe di codice è possibile portare il testo digitato nella prima casella di testo automaticamente tutto in maiuscolo, solamente le iniziali delle parole in maiuscolo (visibile nella seconda casella di testo) e contare il numero di caratteri, compresi gli spazi, nella terza casella di testo.
Il risultato in figura.

Private Sub Text1_Change()
Text3.Text = StrConv(Text1.Text, vbProperCase)
End Sub

Private Sub Text1_KeyPress(KeyAscii As Integer)
KeyAscii = Asc(UCase(Chr(KeyAscii)))
End Sub

Private Sub Text2_Change()
Label1.Caption = "Char: " & Len(Text2.Text)
End Sub

martedì 3 settembre 2013

Controllo Listbox in Visual Basic 6 e associazione elementi

In questo esempio vengono caricate le categorie dal database Northwind di Microsoft su di una Listbox e a partire da una categoria selezionata si faranno vedere i prodotti associati in una seconda Listbox.
Prima di caricare questo codice nelle form di Visual Basic è necessario fare un riferimento al componente Microsoft ActiveX Data Objects 2.8 Library come mostrato nella figura successiva.
L'esempio in questo caso mostra come far visualizzare i dati all'evento Load della form per la prima Listbox, e successivamente all'evento "doppio click" o double-click per la seconda Listbox.

Option Explicit
Dim Conn As ADODB.Connection
Dim rsData As ADODB.Recordset
Dim msgError, strConDbAccess As String
Dim i As Integer

Private Sub Form_Load()

Call LoadDataFromDb

End Sub

Function LoadDataFromDb()
On Error GoTo errorDB
DoEvents

'stringa di connessione al db NWIND
strConDbAccess = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & "c:\NWIND.MDB"

Set Conn = New ADODB.Connection
With Conn
.CommandTimeout = 20
.CursorLocation = adUseClient
.Open strConDbAccess
End With

Set rsData = New ADODB.Recordset
rsData.CursorLocation = adUseServer
rsData.Open "SELECT * FROM Categories ORDER BY CategoryName;", _
Conn, adOpenKeyset, adLockOptimistic, adCmdText

'caricamento dati
For i = 0 To rsData.RecordCount - 1
List1.AddItem (rsData!CategoryName)
rsData.MoveNext
Next i

rsData.Close
Set rsData = Nothing

'chiusura db
Conn.Close
Set Conn = Nothing

Exit Function
errorDB:
msgError = "Errore DataBase" & Chr(13) & _
"Numero Errore: " & Err.Number & " Descrizione: " & Err.Description
MsgBox msgError, vbCritical + vbOKOnly
End Function


Private Sub List1_DblClick()
On Error GoTo errorDB
DoEvents
List2.Clear

Set Conn = New ADODB.Connection
With Conn
.CommandTimeout = 20
.CursorLocation = adUseClient
.Open strConDbAccess
End With

Set rsData = New ADODB.Recordset
rsData.CursorLocation = adUseServer
rsData.Open "SELECT Products.ProductName FROM Products inner join Categories " & _
"on Categories.Categoryid=Products.CategoryId where " & _
"Categories.CategoryName='" & List1.Text & "' ORDER BY ProductName;", _
Conn, adOpenKeyset, adLockOptimistic, adCmdText

'caricamento dati su seconda lista
For i = 0 To rsData.RecordCount - 1
List2.AddItem (rsData!ProductName)
rsData.MoveNext
Next i

rsData.Close
Set rsData = Nothing

'chiusura db
Conn.Close
Set Conn = Nothing

Exit Sub
errorDB:
msgError = "Errore DataBase" & Chr(13) & _
"Numero Errore: " & Err.Number & " Descrizione: " & Err.Description
MsgBox msgError, vbCritical + vbOKOnly
End Sub

Riferimento in VB6

Struttura form

Risultato