AndroidManifest.xml

//uses-permission internet.

//cleartextTraffic true 설정

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.datatransfer">
<uses-permission android:name="android.permission.INTERNET"/>

<application
android:usesCleartextTraffic="true"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".RegisterActivity"></activity>
<activity android:name=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

 

activity_login.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LoginActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="225dp"
android:orientation="vertical"
android:background="@color/colorPrimary">

<ImageView
android:layout_width="125dp"
android:layout_height="125dp"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:src="@drawable/ic_launcher_foreground"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="hohohoho"
android:textColor="#ffffff"
android:textSize="25dp"
android:textStyle="bold"
android:layout_marginTop="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="register help"
android:textColor="#ffffff"
android:textSize="18dp"
android:textStyle="bold"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<EditText
android:layout_width="280dp"
android:layout_height="wrap_content"
android:hint="ID"
android:layout_gravity="center"
android:padding="10dp"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:id="@+id/userId"
android:drawableStart="@drawable/ic_person_black_24dp"
android:drawableLeft="@drawable/ic_person_black_24dp"
android:layout_marginTop="50dp"
android:background="@color/colorPrimary"/>
<EditText
android:inputType="textPassword"
android:layout_width="280dp"
android:layout_height="wrap_content"
android:hint="password"
android:layout_gravity="center"
android:padding="10dp"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:id="@+id/userPwd"
android:drawableStart="@drawable/ic_https_black_24dp"
android:drawableLeft="@drawable/ic_https_black_24dp"
android:layout_marginTop="10dp"
android:background="@color/colorPrimary"/>
<Button
android:layout_width="280dp"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#ffffff"
android:background="@color/colorPrimaryDark"
android:text="login"
android:id="@+id/loginBtn"
android:layout_marginTop="10dp"
android:layout_gravity="center"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="18dp"
android:layout_marginTop="10dp"
android:text="register"
android:id="@+id/registerBtn"/>
</LinearLayout>
</LinearLayout>

</RelativeLayout>

 

activity_register.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RegisterActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@color/colorPrimary">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="register"
android:textColor="#ffffff"
android:textSize="30dp"
android:textStyle="bold"
android:layout_marginTop="10dp"
android:background="@color/colorPrimary"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<EditText
android:layout_width="280dp"
android:layout_height="wrap_content"
android:hint="ID"
android:layout_gravity="center"
android:padding="10dp"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:id="@+id/userId"
android:drawableStart="@drawable/ic_person_black_24dp"
android:drawableLeft="@drawable/ic_person_black_24dp"
android:layout_marginTop="50dp"
android:background="@color/colorPrimary"/>

<EditText
android:inputType="textPassword"
android:layout_width="280dp"
android:layout_height="wrap_content"
android:hint="password"
android:layout_gravity="center"
android:padding="10dp"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:id="@+id/userPwd"
android:drawableStart="@drawable/ic_https_black_24dp"
android:drawableLeft="@drawable/ic_https_black_24dp"
android:layout_marginTop="10dp"
android:background="@color/colorPrimary"/>
<EditText
android:layout_width="280dp"
android:layout_height="wrap_content"
android:hint="email"
android:layout_gravity="center"
android:padding="10dp"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:id="@+id/userEmail"
android:drawableStart="@drawable/ic_email_black_24dp"
android:drawableLeft="@drawable/ic_email_black_24dp"
android:layout_marginTop="10dp"
android:background="@color/colorPrimary"/>
<Button
android:layout_width="280dp"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#ffffff"
android:background="@color/colorPrimaryDark"
android:text="register"
android:layout_marginTop="10dp"
android:layout_gravity="center"
android:id="@+id/registerBtn"/>
</LinearLayout>
</LinearLayout>

</RelativeLayout>

 

LoginActivity.java

//URL url = new URL("http://www.uccstudent.com/zLogin.jsp");

package com.example.datatransfer;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class LoginActivity extends AppCompatActivity {
EditText userId, userPwd;
Button loginBtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);

userId = (EditText) findViewById(R.id.userId);
userPwd = (EditText) findViewById(R.id.userPwd);
loginBtn = (Button) findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(btnListener);

//register page로 이동
TextView registerButton = (TextView) findViewById(R.id.registerBtn);
registerButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
});
}

class CustomTask extends AsyncTask<String, Void, String>{
String sendMsg, receiveMsg;
@Override
protected String doInBackground(String... strings){
try{
String str;
URL url = new URL("http://10.241.131.162:8080/design/zLogin.jsp");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestMethod("POST");
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
sendMsg = "userId="+strings[0]+"&userPwd="+strings[1];
osw.write(sendMsg);
osw.flush();
if(conn.getResponseCode() == conn.HTTP_OK){
InputStreamReader tmp = new InputStreamReader(conn.getInputStream(), "UTF-8");
BufferedReader reader = new BufferedReader(tmp);
StringBuffer buffer = new StringBuffer();
while ((str = reader.readLine()) != null) {
buffer.append(str);
}
receiveMsg = buffer.toString();
} else {
Log.i("result", conn.getResponseCode()+"error");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return receiveMsg;
}
}

View.OnClickListener btnListener = new View.OnClickListener(){
@Override
public void onClick(View view){
switch(view.getId()){
case R.id.loginBtn:
String loginId = userId.getText().toString();
String loginPwd = userPwd.getText().toString();
try{
String result = new CustomTask().execute(loginId, loginPwd).get();
if(result.equals("true")){
Toast.makeText(LoginActivity.this,"login", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
finish();
}else if(result.equals("false")){
Toast.makeText(LoginActivity.this,"wrong ID or Password",Toast.LENGTH_SHORT).show();
userId.setText("");
userPwd.setText("");
}else if(result.equals("noId")){
Toast.makeText(LoginActivity.this,"it doesn't exist",Toast.LENGTH_SHORT).show();
userId.setText("");
userPwd.setText("");
}
}catch(Exception e){
e.printStackTrace();
}break;
}
}
};
}

 

RegisterActivity.java

//URL url = new URL("http://www.uccstudent.com/zRegister.jsp");

package com.example.datatransfer;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class RegisterActivity extends AppCompatActivity {

EditText userId, userPwd, userEmail;
Button registerBtn;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);

userId = (EditText) findViewById(R.id.userId);
userPwd = (EditText) findViewById(R.id.userPwd);
userEmail = (EditText) findViewById(R.id.userEmail);
registerBtn = (Button) findViewById(R.id.registerBtn);
registerBtn.setOnClickListener(btnListener);
}

//연결과 data전송을 위해
class CustomTask extends AsyncTask<String, Void, String>{
String sendMsg, receiveMsg;
@Override
protected String doInBackground(String... strings){
try{
String str;
URL url = new URL("http://10.241.131.162:8080/design/zRegister.jsp");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestMethod("POST");
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
sendMsg = "userId="+strings[0]+"&userPwd="+strings[1]+"&userEmail="+strings[2];
osw.write(sendMsg);
osw.flush();
if(conn.getResponseCode() == conn.HTTP_OK){
InputStreamReader tmp = new InputStreamReader(conn.getInputStream(), "UTF-8");
BufferedReader reader = new BufferedReader(tmp);
StringBuffer buffer = new StringBuffer();
while ((str = reader.readLine()) != null) {
buffer.append(str);
}
receiveMsg = buffer.toString();
} else {
Log.i("result", conn.getResponseCode()+"error");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return receiveMsg;
}
}

//버튼 클릭시
View.OnClickListener btnListener = new View.OnClickListener(){
@Override
public void onClick(View view){
switch(view.getId()){
case R.id.registerBtn:
String joinId = userId.getText().toString();
String joinPwd = userPwd.getText().toString();
String joinEmail = userEmail.getText().toString();
try{
String result = new CustomTask().execute(joinId, joinPwd, joinEmail).get();
if(result.equals("userId")){
Toast.makeText(RegisterActivity.this,"it already exists", Toast.LENGTH_SHORT).show();
userId.setText("");
userPwd.setText("");
userEmail.setText("");
}else if(result.equals("ok")){
userId.setText("");
userPwd.setText("");
userEmail.setText("");
Toast.makeText(RegisterActivity.this,"registered successfully", Toast.LENGTH_SHORT).show();
}
}catch(Exception e){
e.printStackTrace();
}break;
}
}
};
}

 

zRegister.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ page import = "android.*"%>
<%
String userId = request.getParameter("userId");
String userPwd = request.getParameter("userPwd");
String userEmail = request.getParameter("userEmail");

zDAO zdao = zDAO.getInstance();
String returns = zdao.insertUser(userId, userPwd, userEmail);
out.print(returns);
%>

 

zLogin.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ page import = "android.*"%>
<%
String userId = request.getParameter("userId");
String userPwd = request.getParameter("userPwd");

zDAO zdao = zDAO.getInstance();
String returns = zdao.loginUser(userId, userPwd);
out.print(returns);
%>

 

zDAO.java

package android;

import java.sql.*;

public class zDAO {

private static zDAO instance = new zDAO();

public static zDAO getInstance() {
return instance;
}

public zDAO() {
}

public String insertUser(String userId, String userPwd, String userEmail) {
Connection conn = null;
PreparedStatement pstmt2 = null;
PreparedStatement pstmt1 = null;
ResultSet rs = null;
String returns = "";
String sql2 = "insert into test VALUES(?,?,?)";
String sql1 = "select userId from test where userId=?";
String url = "jdbc:mysql://localhost:3306/jusung1025";
String uId = "***********";
String uPw = "***********";

try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,uId,uPw);
pstmt1 = conn.prepareStatement(sql1);
pstmt1.setString(1, userId);
rs = pstmt1.executeQuery();
if(rs.next()) {
if(rs.getString("userId").equals(userId)){
returns = "userId";
}
}else {
pstmt2 = conn.prepareStatement(sql2);
pstmt2.setString(1, userId);
pstmt2.setString(2, userPwd);
pstmt2.setString(3, userEmail);
pstmt2.executeUpdate();

returns = "ok";
}
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
if(pstmt2 != null) pstmt2.close();
if(pstmt1 != null) pstmt1.close();
if(conn != null) conn.close();
}catch(Exception e) {
e.printStackTrace();
}
    }
return returns;
}

public String loginUser(String userId, String userPwd) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String returns = "";
String sql = "select userId,userPwd from test where userId=?";
String url = "jdbc:mysql://localhost:3306/jusung1025";
String uId = "*******";
String uPw = "********";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,uId,uPw);
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userId);
rs = pstmt.executeQuery();
if(rs.next()) {
if(rs.getString("userId").equals(userId) && rs.getString("userPwd").equals(userPwd)) {
returns = "true";
}else {
returns = "false";
}
}else {
returns = "noId";
}
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
}catch(Exception e) {
e.printStackTrace();
}
}
return returns;
}
}

'android studio' 카테고리의 다른 글

android register db connection using JSP  (0) 2019.09.06
android internet check  (0) 2019.09.05
activity life cycle  (0) 2019.08.14
intent  (0) 2019.08.14
startActivityForResult()(화면전환)  (0) 2019.08.13

0.AndroidManifest.xml

//internet permission

//CleartextTraffic true설정

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.httpproject">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application
android:usesCleartextTraffic="true"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

 

1.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">

<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="ID"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Headline" />

<EditText
android:id="@+id/register_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8" />

</TableRow>

<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="PW"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Headline" />

<EditText
android:id="@+id/register_pw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8" />

</TableRow>

<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_horizontal">

<Button
android:id="@+id/register_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="10"
android:text="회원가입" />
</TableRow>
</TableLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

 

MainActivity.java

//url ip값으로 주기

package com.example.httpproject;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity {

Button registerBtn;
EditText idet, pwet;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

setTitle("ORACLE");

registerBtn = (Button)findViewById(R.id.register_btn);
idet = (EditText)findViewById(R.id.register_id);
pwet = (EditText)findViewById(R.id.register_pw);

registerBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
try {
String result;
String id = idet.getText().toString();
String pwd = pwet.getText().toString();

RegisterActivity task = new RegisterActivity();
result = task.execute(id, pwd).get();
} catch (Exception e) {
Log.i("DBtest", ".....ERROR.....!");
}
}
});

}
}

 

RegisterActivity.java

package com.example.httpproject;

import android.os.AsyncTask;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class RegisterActivity extends AsyncTask<String, Void, String> {
String sendMsg, receiveMsg;

@Override
protected String doInBackground(String... strings) {
try {
String str;

// 접속할 서버 주소 (이클립스에서 android.jsp 실행시 웹브라우저 주소)
URL url = new URL("http://10.241.131.162:8080/android/data.jsp");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestMethod("POST");
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());

// 전송할 데이터. GET 방식으로 작성
sendMsg = "id=" + strings[0] + "&pwd=" + strings[1];

osw.write(sendMsg);
osw.flush();

//jsp와 통신 성공 시 수행
if (conn.getResponseCode() == conn.HTTP_OK) {
InputStreamReader tmp = new InputStreamReader(conn.getInputStream(), "UTF-8");
BufferedReader reader = new BufferedReader(tmp);
StringBuffer buffer = new StringBuffer();

// jsp에서 보낸 값을 받는 부분
while ((str = reader.readLine()) != null) {
buffer.append(str);
}
receiveMsg = buffer.toString();
} else {
// 통신 실패
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

//jsp로부터 받은 리턴 값
return receiveMsg;
}

}

'android studio' 카테고리의 다른 글

android - jsp - database connection  (0) 2019.09.08
android internet check  (0) 2019.09.05
activity life cycle  (0) 2019.08.14
intent  (0) 2019.08.14
startActivityForResult()(화면전환)  (0) 2019.08.13

1. manifiest파일에 다음 내용 추가

MainActivity.java

3.HttpThread.java

'android studio' 카테고리의 다른 글

android - jsp - database connection  (0) 2019.09.08
android register db connection using JSP  (0) 2019.09.06
activity life cycle  (0) 2019.08.14
intent  (0) 2019.08.14
startActivityForResult()(화면전환)  (0) 2019.08.13

Activity life Cycle 은 activity의 상태정보(running, pause, stop)이 바뀌는것을 말한다

실행(running): activity가 화면에 보이면서 실행되어있는 상태로 focus가 있는상태이다

일시정지(pause): 사용자에게는 보이지만 focus를 잃은 상태이다(대화상자가 일부가리고있는경우)

중지(stop): 다른 activity에 의해 완전히 가려진 상태

 

System에서 Activity에 대한 상태정보를 관리하며 그에따른 필요한 method를 자동으로 호출한다

onCreate()

a. memory에 activity가 처음 생성될때

b. activity안에 view들을 설정할때

c. Bundle객체를 이용해 이전상태를 복원할때

d. 다음에는 onStart()가 호출된다

onStart()

a. activity가 화면에 보이기 직전에 호출

b. activity가 화면에 보이면 다음에 onResume()을 호출

c. activity가 화면에서 가려지면 다음에 onStop()호출

onResume()

a. 사용자와 상호작용하기 직전에 호출

onRestart()

a. activity가 중지된 이후에 다시 실행될때 호출

b. 다음에는 onStart()가 호출

onPause()

a. 다른 activity가 실행될때 호출된다

b. 저장되지 않은 data를 저장하는 역할

c. 이상태에서는 activity를 강제종료할수있다

onStop()

a. 더이상 화면에 보이지 않을때 호출

b. 다른 activity가 화면을 가릴때 호출

c. 이상태에서는 system에서 강제종료 가능하다

onDestroy()

a. activity가 없어지기 전에 호출

b. finish()호출되거나, system이 강제종료시키는경우 호출

 

memory에 activity가 생성되었을때 system에서 자동으로 onCreate(), onStart()를 호출

실행후 일시정지될때 onPause()가 호출된다. 일시정지후 다시 실행될때 onResume()이 실행된다.

onPause()는 일시정지나 중지상태로 변할때 호출된다. 

일시정지에서 중지상태로 갈때는 onStop()가 호출된다

중지에서 다시 실행상태로 갈때 onRestart(), onStart(), onResume()이 실행된다

소멸될때에는 onDestroy()가 호출된다.

 

activity_main.xml

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click the below button"
android:textSize="20sp"
tools:layout_editor_absoluteX="106dp"
tools:layout_editor_absoluteY="170dp" />
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="new activity"
android:textSize="20sp"
tools:layout_editor_absoluteX="126dp"
tools:layout_editor_absoluteY="233dp"/>

activity_new.xml

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="new Activity"
android:textSize="30sp"
tools:layout_editor_absoluteX="125dp"
tools:layout_editor_absoluteY="262dp" />

NewActivity.java

public class NewActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);

output("onCreate() call");
}
protected void onStart(){
super.onStart();
output("onStart() call");
}
protected void onRestart(){
super.onRestart();
output("onRestart() call");
}
protected void onResume(){
super.onResume();
output("onResume() call");
}
protected void onPause(){
super.onPause();
output("onPause() call");
}
protected void onStop(){
super.onStop();
output("onStop() call");
}
protected void onDestroy(){
super.onDestroy();
output("onDestroy() call");
}
public void output(String msg){
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
Log.d("new", msg);
}
}

MainAtivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button button = findViewById(R.id.btn1);

button.setOnClickListener(listener);
}
View.OnClickListener listener = new View.OnClickListener(){
public void onClick(View view){
//명시적(Explicit) intent
Intent intent = new Intent(getApplicationContext(), NewActivity.class);
startActivity(intent);
}
};
}

 

 

'android studio' 카테고리의 다른 글

android register db connection using JSP  (0) 2019.09.06
android internet check  (0) 2019.09.05
intent  (0) 2019.08.14
startActivityForResult()(화면전환)  (0) 2019.08.13
activity 추가하기  (0) 2019.08.13

intent는 activity와 acivity사이의 data를 전달하기위해 사용된다

intent를 이용한 method에는 startActivity(), startActivityForResult()

startService(), bindServie(), broadcastIntent()가있다

 

intent의 기본구성요소에는 Action과 Data가 있다

Action은 수행기능을 의미하고 Data는 수행할대상의 data이다

Action에는 ACTION_VIEW, ACTION_EDIT가 있다

 

Intent 안에 여러 유형의 Data가있는데

system에서 data의 format에 맞게 activity를 보여준다

 

다양한 방법으로 Intent를 생성할수 있다

Intent()

Intetnt(Intent *)

Intent(action, uri)

Intent(context, class)

Intetnt(string action, uri, context pacakage, class())

 

명시적(Explicit) Intent는 class 객체나 컴포넌트 이름을 지정함으로 호출대상이 명료해지는경우

암시적(Implicit) Intent는 수행할 Action과 Data를 지정했더라도 호출대상이 지정되어있지않다

암시적 Intent의 anction, data는 MIME Type에의해 자동으로 activity를 찾아서 띄운다

암시적 Intent의 다른속성으로는 부가 데이터(Extras)가있고 getExtra, putExtra를 통해 data를 이동시킨다 

activity_main.xml

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint = "put the telephone(000-0000-0000)"
android:textSize = "20sp"
android:padding = "10dp"
android:layout_marginTop = "100dp"
android:layout_marginBottom="40dp"/>

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="after putting telephone, click the below button"
android:textSize = "15sp"
android:layout_marginBottom = "10dp"/>
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = "call"
android:textSize="20sp"
android:textStyle="bold"
android:onClick = "clickBtn1"
android:layout_gravity="center_horizontal"/>

MainActivity.java

public class MainActivity extends AppCompatActivity {
EditText editText;
TextView textView;

public static final int REQUEST_CODE=111;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

editText = findViewById(R.id.editText);
textView = findViewById(R.id.textView);
}
public void clickBtn1(View view){
String telNumber = editText.getText().toString();

// 암시적(implicit) Intent
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(telNumber));
startActivity(intent);

/* 명시적 intent 1.호출대상 객체(class)를 지정
Intent intent = new Intent(getApplicationContext(), Main2Activity.class)
startActivityForResult(intent, REQUEST_CODE);
*/
/* 명시적 intent 2.
Intent intent = new Intent();
ComponentName componentName = new ComponentName("com.example.myapplication", "come.example.myapplication.Main2Activity");

intent.setComponent(componentName);
startActivityForResult(intent, REQUEST_CODE);
*/
}
}

 

'android studio' 카테고리의 다른 글

android internet check  (0) 2019.09.05
activity life cycle  (0) 2019.08.14
startActivityForResult()(화면전환)  (0) 2019.08.13
activity 추가하기  (0) 2019.08.13
Recycler View  (0) 2019.08.13

startActivityForResult(intent, resultCode)

resultCode를 이용해 activity 1 or activity 2에 request code를 보내고

setResult(응답코드, intent)을 이용해 activity로부터 response code를 받는다

finish() method는 request 와 response 처리가 끝난후 activity를 화면애서 없앨때 사용한다

//MainActivity에서 NewActivity로 startActivityForReuslt()를 이용해 requestCode를 보내고

NewActivity에서 setResult()를 이용해 reponseCode를 보낸후 finish()를이용해 화면을 없애준다

MainActivity에서 onActivityResult()를 이용해 responseCode를 처리한다

//onActivityResult(int RequestCode, int ResultCode, intent)

 

activity_main.xml

<TextView
android:id="@+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click the button to open new screen"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.288" />

<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="256dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:onClick="btnClicked"
android:text="here"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

new_activity.xml

<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="360dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:text="go back to main"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

AndroidManifest.xml

<activity android:name=".Main2Activity"
android:label="new activity"
android:theme="@style/Theme.AppCompat.Dialog"></activity>

Main2Activity.java

public class Main2Activity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_activity);

Button button = findViewById(R.id.btn2);
button.setOnClickListener(listener);
}
View.OnClickListener listener = new View.OnClickListener(){
public void onClick(View view){
Intent intent = new Intent();
intent.putExtra(name: "message", value: "transfered message");
//response
setResult(RESULT_OK, intent);
//activity close
finish();
}
};
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
public static final int REQUEST_CODE = 111;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button button = findViewById(R.id.btn1);
// button.setOnClickListener(listener);
}
//OnClickListener를 이용할수도있고 btnClicked method를 만들어서 작동할수도있다
// View.OnClickListener listener = new View.OnClickListener(){
// public void onClick(View view){
// Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
// startActivityForResult(intent, REQUEST_CODE);
// }
// };
public void btnClicked(View view){
Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
startActivityForResult(intent, REQUEST_CODE);
}
//main화면으로 이동
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);

if(requestCode == REQUEST_CODE){
Toast.makeText(getApplicationContext(),
"onActivity() call, requestCode:"+requestCode+", responseCode: "+resultCode, Toast.LENGTH_LONG).show();
}
if(resultCode == RESULT_OK){
String responseMsg = data.getStringExtra(name: "message");
Toast.makeText(getApplicationContext(), text: "response message" +responseMsg, Toast.LENGTH_LONG).show();
}
}
}

 

 

'android studio' 카테고리의 다른 글

activity life cycle  (0) 2019.08.14
intent  (0) 2019.08.14
activity 추가하기  (0) 2019.08.13
Recycler View  (0) 2019.08.13
custom dialog  (0) 2019.08.13

새로운 activity를 추가

1. Manifest file에 ativity tag가 자동으로 추가된다

2. 새로운 activity에 layout을 정의 

3. MainActivity에 새 Activity 띄우기(startActivity(), startActivityForResult())

4. 새 Activity에서 처리결과를 보내기(setResult())

5. MainActivity에서 onActivityResult() 를이용해 응답처리

//new\activity\empty activity

activity_main.xml

<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="136dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:text="New activity"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

activity_main2.xml

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="260dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:text="new activity"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

AndroidManifest.xml

<activity android:name=".Main2Activity"
android:label = "new activity"
android:theme = "@style/Theme.AppCompat.Dialog.Alert"></activity>

MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button button = findViewById(R.id.btn1);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
startActivity(intent);
}
});
}
}

'android studio' 카테고리의 다른 글

intent  (0) 2019.08.14
startActivityForResult()(화면전환)  (0) 2019.08.13
Recycler View  (0) 2019.08.13
custom dialog  (0) 2019.08.13
alert dialog  (0) 2019.08.13

activity_main.xml

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>

item_style.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView"
android:layout_width="80dp"
android:layout_height="80dp"
android:padding = "5dp"
android:src="@mipmap/ic_launcher"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="5dp">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text = "agency name"
android:textSize = "30sp"/>
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="contacts"
android:textColor = "#f0f"
android:textSize = "24sp"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>

Agent.java

public class Agent {
String name;
String telNumber;

public Agent(String name, String telNumber){
this.name = name;
this.telNumber = telNumber;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getTelNumber(){
return telNumber;
}
public void setTelNumber(String telNumber){
this.telNumber = telNumber;
}
}

AgentAdapter.java

public class AgentAdapter extends RecyclerView.Adapter<AgentAdapter.ViewHolder>{
ArrayList<Agent> items = new ArrayList<Agent>();

public ViewHolder onCreateViewHolder(ViewGroup vg, int viewType){
LayoutInflater inflater = LayoutInflater.from(vg.getContext());
View itemView = inflater.inflate(R.layout.item_style, vg, false);

//view 객채를 담아서 새로생성된 ViewHolder 객체를 리턴한다
return new ViewHolder(itemView);
}
public void onBindViewHolder(ViewHolder vh, int position){
Agent item = items.get(position);
vh.setItem(item);
}//재사용할때 호출되는 method
public int getItemCount(){
return items.size();
}
public void addItem(Agent item){
items.add(item);
}
public void setItem(ArrayList<Agent> items){
this.items = items;
}
public Agent getItem(int position){
return items.get(position);
}
public void setItem(int position, Agent item){
items.set(position, item);
}
static class ViewHolder extends RecyclerView.ViewHolder{
TextView textView1;
TextView textView2;

public ViewHolder(View itemView){
super(itemView);

textView1 = itemView.findViewById(R.id.textView1);
textView2 = itemView.findViewById(R.id.textView2);
}
//item setting
public void setItem(Agent item){
textView1.setText(item.getName());
textView2.setText(item.getTelNumber());
}
}
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

RecyclerView recyclerView = findViewById(R.id.recyclerView);

LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);

AgentAdapter adapter = new AgentAdapter();

adapter.addItem(new Agent("busan", "123123123"));
adapter.addItem(new Agent("hoho", "123123123"));
adapter.addItem(new Agent("hoho", "123123123"));
adapter.addItem(new Agent("hoho", "123123123"));
adapter.addItem(new Agent("hoho", "123123123"));

recyclerView.setAdapter(adapter);
}
}

'android studio' 카테고리의 다른 글

startActivityForResult()(화면전환)  (0) 2019.08.13
activity 추가하기  (0) 2019.08.13
custom dialog  (0) 2019.08.13
alert dialog  (0) 2019.08.13
방향전환 event로 activity 유지하기  (0) 2019.08.13

+ Recent posts