|
|
|
Android - การส่งค่าล็อคอินไป ยังหน้า สอง และหน้าสาม รบกวนดูให้หน่อยน่ะค่ะ |
|
|
|
|
|
|
|
พอดีลองศึกษากำลังทำโปรเจคอยู่ค่ะ ลองทำตามลิงค์นี้ ค่ะ
https://www.thaicreate.com/mobile/android-check-login-user-password.html
(ในตัวอย่างล็อคอินเสร็จก็จะไปยังหน้าเเสดงข้อมูลสมาชิกเลย)
เเต่อยากให้ล็อคอินเสร็จแล้วไปยังหน้า 2 แล้วกดปุ่มไป หน้าสามคือหน้าเเสดงข้อมูลที่ล็อคอิน
เลยลองเขียน code ในหน้า 2 ดู เพื่อรับค่าและส่งค่าไปหน้า3 เเต่ค่ามันไม่ยอมส่งไปยังไงรบกวนดูให้หน่อยน่ะค่ะ
หน้าล็อคอิน
Code (Java)
package com.myapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
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 org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final AlertDialog.Builder ad = new AlertDialog.Builder(this);
// txtUsername & txtPassword
final EditText txtUser = (EditText)findViewById(R.id.txtUsername);
final EditText txtPass = (EditText)findViewById(R.id.txtPassword);
// btnLogin
final Button btnLogin = (Button) findViewById(R.id.btnLogin);
// Perform action on click
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String url = "https://www.thaicreate.com/android/checkLogin.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("strUser", txtUser.getText().toString()));
params.add(new BasicNameValuePair("strPass", txtPass.getText().toString()));
/** Get result from Server (Return the JSON Code)
* StatusID = ? [0=Failed,1=Complete]
* MemberID = ? [Eg : 1]
* Error = ? [On case error return custom error message]
*
* Eg Login Failed = {"StatusID":"0","MemberID":"0","Error":"Incorrect Username and Password"}
* Eg Login Complete = {"StatusID":"1","MemberID":"2","Error":""}
*/
String resultServer = getHttpPost(url,params);
/*** Default Value ***/
String strStatusID = "0";
String strMemberID = "0";
String strError = "Unknow Status!";
JSONObject c;
try {
c = new JSONObject(resultServer);
strStatusID = c.getString("StatusID");
strMemberID = c.getString("MemberID");
strError = c.getString("Error");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Prepare Login
if(strStatusID.equals("0"))
{
// Dialog
ad.setTitle("Error! ");
ad.setIcon(android.R.drawable.btn_star_big_on);
ad.setPositiveButton("Close", null);
ad.setMessage(strError);
ad.show();
txtUser.setText("");
txtPass.setText("");
}
else
{
Toast.makeText(MainActivity.this, "Login OK", Toast.LENGTH_SHORT).show();
Intent newActivity = new Intent(MainActivity.this,LoginNext.class);
newActivity.putExtra("MemberID", strMemberID);
startActivity(newActivity);
}
}
});
}
public String getHttpPost(String url,List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
หน้าสอง
Code (Java)
public class LoginNext extends Activity{
String strMemberID = "0";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_two);
Bundle bundle = getIntent().getExtras();
String data = bundle.getString("MemberID");
Button btngo = (Button) findViewById(R.id.btngo);
btngo.setOnClickListener (new OnClickListener () {
public void onClick(View V) {
Intent data = new Intent(LoginNext.this,DetailActivity.class);
data.putExtra("MemberID", strMemberID);
startActivity(data);
}
});
}}
หน้าสาม เเสดงข้อมูล
Code (Java)
package com.myapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
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 org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.widget.Button;
import android.widget.TextView;
public class DetailActivity extends Activity {
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
showInfo();
// btnBack
final Button btnBack = (Button) findViewById(R.id.btnBack);
// Perform action on click
btnBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent newActivity = new Intent(DetailActivity.this,MainActivity.class);
startActivity(newActivity);
}
});
}
public void showInfo()
{
// txtMemberID,txtMemberID,txtUsername,txtPassword,txtName,txtEmail,txtTel
final TextView tMemberID = (TextView)findViewById(R.id.txtMemberID);
final TextView tUsername = (TextView)findViewById(R.id.txtUsername);
final TextView tPassword = (TextView)findViewById(R.id.txtPassword);
final TextView tName = (TextView)findViewById(R.id.txtName);
final TextView tEmail = (TextView)findViewById(R.id.txtEmail);
final TextView tTel = (TextView)findViewById(R.id.txtTel);
String url = "https://www.thaicreate.com/android/getByMemberID.php";
Intent intent= getIntent();
final String MemberID = intent.getStringExtra("MemberID");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sMemberID", MemberID));
/** Get result from Server (Return the JSON Code)
*
* {"MemberID":"2","Username":"adisorn","Password":"adisorn@2","Name":"Adisorn Bunsong","Tel":"021978032","Email":"[email protected]"}
*/
String resultServer = getHttpPost(url,params);
String strMemberID = "";
String strUsername = "";
String strPassword = "";
String strName = "";
String strEmail = "";
String strTel = "";
JSONObject c;
try {
c = new JSONObject(resultServer);
strMemberID = c.getString("MemberID");
strUsername = c.getString("Username");
strPassword = c.getString("Password");
strName = c.getString("Name");
strEmail = c.getString("Email");
strTel = c.getString("Tel");
if(!strMemberID.equals(""))
{
tMemberID.setText(strMemberID);
tUsername.setText(strUsername);
tPassword.setText(strPassword);
tName.setText(strName);
tEmail.setText(strEmail);
tTel.setText(strTel);
}
else
{
tMemberID.setText("-");
tUsername.setText("-");
tPassword.setText("-");
tName.setText("-");
tEmail.setText("-");
tTel.setText("-");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getHttpPost(String url,List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Tag : Mobile, Mobile
|
ประวัติการแก้ไข 2015-03-08 21:56:45
|
|
|
|
|
Date :
2015-03-08 21:53:10 |
By :
teeneeone |
View :
1232 |
Reply :
3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ถ้าอยากให้เก็บค่าไปยัง Activity หรือหน้าอื่น ๆ อาจจะต้องเก็บลงใน SharedPreferences ครับ ซึ่งจะทำงานคล้าย ๆ กับ Session ที่เมื่อประกาศตัวแปรล้วสามารถเรียกใช้ในหน้าอื่น ๆ ได้
ตัวอย่างการใช้ SharedPreferences
UserHelper.java
public class UserHelper {
Context context;
SharedPreferences sharedPerfs;
Editor editor;
// Prefs Keys
static String perfsName = "UserHelper";
static int perfsMode = 0;
public UserHelper(Context context) {
this.context = context;
this.sharedPerfs = this.context.getSharedPreferences(perfsName, perfsMode);
this.editor = sharedPerfs.edit();
}
public void createSession(String key) {
editor.putBoolean("isLogin", true);
editor.putString("userID", key);
editor.commit();
}
public void deleteSession() {
editor.clear();
editor.commit();
}
public boolean isLogin() {
return sharedPerfs.getBoolean("isLogin", false);
}
public String getUserID() {
return sharedPerfs.getString("userID", null);
}
}
วิธีใช้
Code (Java)
UserHelper usrHelper = new UserHelper(this);
// Create Session
usrHelper.createSession(ID);
// Delete Session
usrHelper.deleteSession();
// Check Login
if (usrHelper.isLogin()) {
} else {
}
// Get UserID
usrHelper.getUserID()
|
|
|
|
|
Date :
2015-03-09 07:01:52 |
By :
mr.win |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ผมใช้ SharedPreferences เข้าช่วยแต่มันไม่ดึงข้อมูลมาจาก Mysql อ่าครับเจ้าของกระทู้ ทำได้ยังอ่า
|
|
|
|
|
Date :
2015-03-09 21:14:09 |
By :
crono001 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Load balance : Server 05
|