- Forum-Beiträge: 26
21.07.2012, 00:03:25 via Website
21.07.2012 00:03:25 via Website
Ich versuche mir gerade ein gescheites Konzept für JSON Aufrufe innerhalb der Anwendung zu überlegen. Wie macht ihr da die Architektur?
Mich interessiert vor allem wie ihr mit asynchronen Threads bei Netzwerkaufrufen umgeht. Ich übergebe hier nämlich den Context der Activity und lasse dann die Methode ausführen wenn der Thread in meinem JSON Service beendet ist.
Das hier funktioniert... ich frag mich nur ob es sauber ist. Ein Beispiel für eine Authentifierung mit einem PHP Backend:
2 include("configuration/database.php");
3 $json = file_get_contents('php://input');
4 $obj = json_decode($json);
5 $result2=mysql_query("SELECT id, activationcode FROM users WHERE email='".$obj->{'email'}."' AND password='".$obj->{'password'}."'") or die(mysql_error());
6
7 $user="nouser";
8 while ($row = mysql_fetch_array($result2, MYSQL_NUM)) {
9 $user=$row[0];
10 $activationcode=$row[1];
11 }
12
13 $posts = array(1);
14
15 if($user!="nouser")
16 {
17 if($activationcode=="activated")
18 {
19 session_start();
20 session_register("userid");
21 $_SESSION["userid"] =$user;
22 header('Content-type: application/json');
23 echo "success";
24 }
25 else
26 {
27 $registrationcode=substr(md5($obj->{'email'}." ".$obj->{'password'}),6);
28 mysql_query("UPDATE users SET activationcode='".$registrationcode."' WHERE email='".$obj->{'email'}."'") or die(mysql_error());
29 mail($obj->{'email'},"Registrationcode for contactupload.com","Hello!<br><br>\n You or someone else has registered this email address via mobile phone.<br><br>\nThe generated registrationcode is ".$registrationcode.".<br><br>\nPlease type this registrationcode in the register section of the contact sync app.<br><br>\nWith best regards,<br>\ncontactupload.com");
30 echo "not activated";
31 }
32 }
33 else
34 {
35 echo "not registered";
36 }
37 mysql_close($con);
38?>
Das hier ist die MainActivity, die onLoginResult implementiert, welche aufgerufen wird wenn der Thread des JSON Aufrufs (siehe weiter unten) beendet ist:
2
3import com.caprisoft.contactupload.services.BjoernsServiceCaller;
4
5import android.os.Bundle;
6import android.app.Activity;
7import android.util.Log;
8import android.view.Menu;
9import android.view.View;
10import android.widget.EditText;
11import android.widget.Toast;
12
13public class MainActivity extends Activity {
14
15 private EditText email = null;
16 private EditText passwort = null;
17
18 /** Called when the user selects the Send button */
19 public void onClickLoginButton(View view) {
20 // Do something in response to button
21 Log.d(this.getClass().toString(), "Login Button gedrückt!");
22 BjoernsServiceCaller.getInstance().loginUser(this, email.getText().toString(), passwort.getText().toString());
23 }
24
25 /** Called when the user selects the Send button */
26 public void onClickRegisterButton(View view) {
27 // Do something in response to button
28 Log.d(this.getClass().toString(), "Register Button gedrückt!");
29 }
30
31 public void onLoginResult(String text)
32 {
33 Toast.makeText(this, "HALLO: "+text, Toast.LENGTH_LONG).show();
34 }
35
36 @Override
37 public void onCreate(Bundle savedInstanceState) {
38 super.onCreate(savedInstanceState);
39 setContentView(R.layout.activity_main);
40
41 email = (EditText) findViewById(R.id.textUsername);
42 passwort = (EditText) findViewById(R.id.textPassword);
43 }
44
45 @Override
46 public boolean onCreateOptionsMenu(Menu menu) {
47 getMenuInflater().inflate(R.menu.activity_main, menu);
48 return true;
49 }
50
51
52}
Und hier wollte ich die Services aufrufenn:
2
3import java.io.BufferedReader;
4import java.io.InputStreamReader;
5
6import org.apache.http.HttpResponse;
7import org.apache.http.client.HttpClient;
8import org.apache.http.client.methods.HttpPost;
9import org.apache.http.entity.StringEntity;
10import org.apache.http.impl.client.DefaultHttpClient;
11import org.apache.http.message.BasicHeader;
12import org.apache.http.params.HttpConnectionParams;
13import org.apache.http.protocol.HTTP;
14import org.json.JSONArray;
15import org.json.JSONObject;
16import org.json.JSONTokener;
17
18import com.caprisoft.contactupload.MainActivity;
19
20import android.content.Context;
21import android.os.Looper;
22import android.util.Log;
23import android.widget.Toast;
24
25
26public class BjoernsServiceCaller
27{
28
29 final String authenticationURL = "http://www.capri-soft.de/android/authenticationservice.php";
30 private static BjoernsServiceCaller instance = null;
31 private BjoernsServiceCaller() {}
32
33
34 /**
35 * Statische Methode, liefert die einzige Instanz dieser
36 * Klasse zurück
37 */
38 public static BjoernsServiceCaller getInstance()
39 {
40 if (instance == null)
41 {
42 instance = new BjoernsServiceCaller();
43 }
44 return instance;
45 }
46
47
48 public void loginUser(final MainActivity ctx, final String email, final String password)
49 {
50 Thread t = new Thread()
51 {
52 public void run()
53 {
54 Looper.prepare(); //For Preparing Message Pool for the child Thread
55
56 HttpClient client = new DefaultHttpClient();
57 HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
58 HttpResponse response;
59 JSONObject json = new JSONObject();
60 try
61 {
62 HttpPost post = new HttpPost(authenticationURL);
63 json.put("email", email);
64 json.put("password", password);
65 StringEntity se = new StringEntity( json.toString());
66 se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
67 post.setEntity(se);
68 response = client.execute(post);
69 /*Checking response */
70 if(response!=null)
71 {
72 BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
73 String derText = reader.readLine();
74 ctx.onLoginResult(derText);
75 }
76
77 }
78 catch(Exception e)
79 {
80 e.printStackTrace();
81 }
82 Looper.loop(); //Loop in the message queue
83 }
84 };
85 t.start();
86 }
87}
Wie würdet ihr das machen?
Empfohlener redaktioneller Inhalt
Mit Deiner Zustimmung wird hier ein externer Inhalt geladen.
Mit Klick auf den oben stehenden Button erklärst Du Dich damit einverstanden, dass Dir externe Inhalte angezeigt werden dürfen. Dabei können personenbezogene Daten an Drittanbieter übermittelt werden. Mehr Infos dazu findest Du in unserer Datenschutzerklärung.