1, SpringBoot is used in IDEA to manage the back-end requests, which is the basic framework in IDEA
1.Spring integrates mybatis
1. Enter Dane and import the dependencies required by SSM framework
2. Create yml file
//Create yml file spring: datasource: type: com.alibaba.druid.pool.DruidDataSource druid: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/shopping?serverTimezone=GMT%2B8 username: root password: root max-active: 20 max-wait: 6000 min-idle: 1 test-on-borrow: true test-on-return: true thymeleaf: mode: HTML encoding: UTF-8 cache: false mybatis: //mapper/xml corresponds to the generated path mapper-locations: classpath*:com/example/androidtest/mapper/*Mapper.xml //configuration file config-location: classpath:mybatis-config.xml shopping: host: http://img.neuedu.com
//Create mybatis config. In the resources file XML file <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="logImpl" value="LOG4J"/> </settings> <typeAliases> </typeAliases> </configuration>
2. Create a database and import it using reverse engineering
1. Establish the required database
2. Create and use generatorconfig. In the resources file XML file for reverse engineering configuration
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!--Import attribute configuration--> <!--Specifies the of a specific database jdbc drive jar Package location,Need to find your own jar Package location--> <classPathEntry location="D:\\alijavaweb\\mysql\\mysql-connector-java\\8.0.15\\mysql-connector-java-8.0.15.jar" /> <context id="context" targetRuntime="MyBatis3"> <!-- optional,Designed to create class Controls annotations when --> <commentGenerator> <property name="suppressDate" value="true"/> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--jdbc Database connection for -->//The configuration is the same as that in yml <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/shopping?serverTimezone=GMT%2B8" userId="root" password="root"> </jdbcConnection> <!-- Not required, type processor, in database type and java Conversion control between types--> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- Model Model generator,Used to generate primary keys key Class, record class and query Example class targetPackage Specify generated model Package name where the build is located targetProject Specify the path under the project --> <!-- Generate the entity class corresponding to the table--> <javaModelGenerator targetPackage="com.example.androidtest.pojo" targetProject="./src/main/java"> <!-- Whether to allow sub packages, i.e targetPackage.schemaName.tableName --> <property name="enableSubPackages" value="false"/> <!-- Right model Add constructor --> <property name="constructorBased" value="true"/> <!-- Class CHAR Type of column trim operation --> <property name="trimStrings" value="true"/> <!-- Established Model Is the object immutable or generated Model Object will not have setter Method, only construction method --> <property name="immutable" value="false"/> </javaModelGenerator> <!--mapper The directory where the mapping file is generated generates the corresponding mapping file for each database table SqlMap file --> <!--Generate corresponding mapper.xml file--> <sqlMapGenerator targetPackage="com.example.androidtest.mapper" targetProject="./src/main/resources"> <property name="enableSubPackages" value="false"/> </sqlMapGenerator> <!-- Client code to generate easy-to-use code for Model Object and XML Code of the configuration file type="ANNOTATEDMAPPER",generate Java Model And annotation based Mapper object type="MIXEDMAPPER",Generate annotation based Java Model And corresponding Mapper object type="XMLMAPPER",generate SQLMap XML Documentation and independent Mapper Interface --> <!-- targetPackage: mapper Interface dao Generated location --> <!--Generate corresponding mapper Interface file--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.androidtest.dao" targetProject="./src/main/java"> <!-- enableSubPackages:Whether to let schema As the suffix of the package --> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!--take tableName Change the name and quantity of your own database table--> <table tableName="nite_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> <!-- <table tableName="nite_category" domainObjectName="Category" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>--> <!-- <table tableName="nite_product" domainObjectName="Product" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>--> <!-- <table tableName="nite_cart" domainObjectName="Cart" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>--> <!-- <table tableName="nite_order" domainObjectName="Order" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>--> <!-- <table tableName="nite_item" domainObjectName="Item" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>--> <!-- <table tableName="nite_shipping" domainObjectName="Shipping" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>--> <!-- geelynote mybatis Construction of plug-ins --> </context> </generatorConfiguration>
3. Encapsulate the highly available ServerResponse object
Experience: why use this encapsulated object? Originally, we returned an entity class object, such as Jianzhi selectByid(int id); However, if the encapsulated type of ServerResponse is used, we can return an additional status code to facilitate us to identify the correct / error information.
1. Encapsulate a ServerResponse class to return status, information and prompt
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.annotation.JsonNaming; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import lombok.Data; /** * Encapsulates the unified entity class returned by the front end * @param <T> */ @Data @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)//Contains only non empty fields public class ServerResponse<T> { private int status; //Status 0; Interface call succeeded private T data; //Generic T, when status=0, encapsulates the returned data into data private String msg; //Prompt information private ServerResponse(){} private ServerResponse(int status){ this.status = status; } private ServerResponse(int status, T data){ this.status = status; this.data = data; } private ServerResponse(int status, T data, String msg){ this.status = status; this.data = data; this.msg = msg; } @JsonIgnore public boolean isSuccess(){ return this.status == 0; } public static ServerResponse createServerResponseBySuccess(){ return new ServerResponse(0); } /** *<T>The generic method is represented by the method name followed */ public static <T> ServerResponse createServerResponseBySuccess(T data){ return new ServerResponse(0,data); } public static <T> ServerResponse createServerResponseBySuccess(T data,String msg){ return new ServerResponse(0,data,msg); } public static ServerResponse createServerResponseByFail(int status){ return new ServerResponse(status); } public static ServerResponse createServerResponseByFail(int status,String msg){ return new ServerResponse(status,null,msg); } }
2. Encapsulate an enum class ResponseCode, which is used to put the status code and status information
public enum ResponseCode { //The status information is placed in the; front USERNAME_NOT_EMPTY(1,"User name cannot be empty"), PASSWORD_NOT_EMPTY(2,"Password cannot be empty"), USERNAME_NOT_EXIST(3,"user name does not exist"), PASSWORD_ERROR(4,"Password error"), PARAMETER_NOT_EMPTY(5,"Parameter cannot be empty"), EMAIL_NOT_EMPTY(6,"Mailbox cannot be empty"), QUESTION_NOT_EMPTY(7,"Secret protection problem cannot be empty"), ANSWER_NOT_EMPTY(8,"Secret protection answer cannot be empty"), PHONE_NOT_EMPTY(9,"Phone number cannot be empty"), USERNAME_EXIST(10,"User name already exists"), EMAIL_EXIST(11,"Mailbox already exists"), REGISTER_FAIL(12,"login has failed"), NEED_LOGIN(13,"Not logged in"), USERINFO_UPDATE_FAIL(14,"User information modification failed"), ; private int code; private String msg; ResponseCode(int code,String msg){ this.code = code; this.msg = msg; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
3. Create a DateUtil time tool class
import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import java.util.Date; /* Time formatting tool class */ public class DateUtil { public static final String STANDARD = "yyyy-MM-dd HH:mm:ss"; //Convert String to Date public static Date string2Date(String strDate){ DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(STANDARD); DateTime dateTime = dateTimeFormatter.parseDateTime(strDate); return dateTime.toDate(); } //Convert Date to String public static String date2String(Date date){ if(date == null){ return StringUtils.EMPTY; } DateTime dateTime = new DateTime(date); return dateTime.toString(STANDARD); } }
II Android build
1. Android connects to the Internet and interacts with IDEA
1. First, add the codes at both ends in the build. Of the corresponding module In gradle, we can use OkHttp protocol to obtain URL data later
implementation'com.squareup.okhttp3:okhttp:3.10.0' implementation 'com.google.code.gson:gson:2.8.6'
2. Add OkHttpCallback and OkhttpUtils files under utils package
//OkHttpUtils file is used to obtain the information of get, post, downFile and other methods on the URL public class OkHttpUtils { private static final OkHttpClient CLIENT = new OkHttpClient(); public static void get(String url,OkHttpCallback Callback){ Callback.url = url; //Build request header Request request = new Request.Builder().url(url).build(); //Receive the response from the server CLIENT.newCall(request).enqueue(Callback); } public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); public static void post(String url,String json,OkHttpCallback callback){ callback.url = url; RequestBody body = RequestBody.create(JSON,json); Request request = new Request.Builder().url(url).post(body).build(); CLIENT.newCall(request).enqueue(callback); } public static void downFile(String url,final String saveDir,OkHttpCallback callback){ callback.url = url; Request request = new Request.Builder().url(url).build(); CLIENT.newCall(request).enqueue( callback); } }
import android.util.Log; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; //Listen to the response of the server and obtain the correct / error information of the server public class OkHttpCallback implements Callback { private final String TAG =com.example.onlinecareer.util.OkHttpCallback.class.getSimpleName(); public String url; public String result; //Interface call succeeded @Override public void onResponse(Call call, Response response) throws IOException { Log.d(TAG,"url:"+url); //Get interface data on success result = response.body().string().toString(); Log.d(TAG,"Request succeeded:"+result); //Call onFinish to output the obtained information. You can use hashmap to obtain the required value and store it by rewriting onFinish() method onFinish("success",result); } public void onFailure(Call call,IOException e){ Log.d(TAG,"url:"+url); Log.d(TAG,"request was aborted:"+e.toString()); //The request failed and the reason for the output failure onFinish("failure",e.toString()); } public void onFinish(String status,String msg){ Log.d(TAG,"url:"+url + "status:" + status+"msg:"+msg); } }
3. Operate in the header file xml
<!--Insert in head--> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!--stay application Insert in label--> android:networkSecurityConfig="@xml/network_config" android:usesCleartextTraffic="true"
4. Create an xml package in res, which contains network_config.xml file
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <base-config cleartextTrafficPermitted="true" /> </network-security-config>
2. Create a class that contains Static global variables for subsequent use
public class CommonData { //Login status public static boolean isLogin=false; //Login user data public static HashMap<String, Object> user_hashMap; public static HashMap<String, Object> user_hashMap1; //All user data public static ArrayList<HashMap<String, Object>> list =new ArrayList<HashMap<String,Object>>(); }
3. Write the Baseadapter class to enable listview to be implemented with a layout as an example
public class JobAdapter extends BaseAdapter { //Define a dynamic array private List<HashMap<String, Object>> data; private Context context; //The data here is the hashmap data from OneFragment public JobAdapter(Context context, List<HashMap<String, Object>> data) { this.context = context; this.data = data; } @Override public int getCount() { return data.size(); } @Override public HashMap<String, Object> getItem(int position) { return data.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { //Associated with the layout of the target if (convertView == null) { convertView = View.inflate(context, R.layout.item_job, null); new ViewHolder(convertView); } //Gets the control of the target layout final ViewHolder holder = (ViewHolder) convertView.getTag(); HashMap<String, Object> hashMap=getItem(position); //Put the data obtained from hashmap into the control list holder.iv_job_icon.setBackgroundResource((Integer)hashMap.get("img")); holder.tv_job_name.setText(hashMap.get("name").toString()); holder.tv_job_company.setText(hashMap.get("company").toString()); holder.tv_job_time.setText(hashMap.get("time").toString()); holder.tv_job_salary.setText(hashMap.get("salary").toString()); holder.tv_job_type.setText(hashMap.get("jobType").toString()); return convertView; } //Corresponds to the control of the target layout class ViewHolder { public ImageView iv_job_icon; public TextView tv_job_name; public TextView tv_job_company; public TextView tv_job_time; public TextView tv_job_salary; public TextView tv_job_type; public ViewHolder(View view) { iv_job_icon = (ImageView) view.findViewById(R.id.iv_job_icon); tv_job_name = (TextView) view.findViewById(R.id.tv_job_name); tv_job_company = (TextView) view.findViewById(R.id.tv_job_company); tv_job_time = (TextView) view.findViewById(R.id.tv_job_time); tv_job_salary = (TextView) view.findViewById(R.id.tv_job_salary); tv_job_type = (TextView) view.findViewById(R.id.tv_job_type); view.setTag(this); } } }
4. Fragment management to achieve the effect similar to ajax.
1. Create a unified management main
@SuppressLint("NewApi") public class MainActivity extends Activity implements CompoundButton.OnCheckedChangeListener { private FrameLayout frameLayout; public OneFragment oneFragment; public TwoFragment twoFragment; public ThreeFragment threeFragment; public Fragment fa; private RadioButton radioButton1, radioButton2, radioButton3; private int currentTab = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initView(); initEvent(); } @Override protected void onResume() { super.onResume(); setSelect(currentTab); } private void initView() { frameLayout = (FrameLayout) findViewById(R.id.fl_content); radioButton1 = (RadioButton) findViewById(R.id.radioButton1); radioButton2 = (RadioButton) findViewById(R.id.radioButton2); radioButton3 = (RadioButton) findViewById(R.id.radioButton3); } //Enter the page represented by 0 at the beginning private void initEvent() { // TODO Auto-generated method stub radioButton1.setOnCheckedChangeListener(this); radioButton2.setOnCheckedChangeListener(this); radioButton3.setOnCheckedChangeListener(this); setSelect(0); radioButton1.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.home_selected), null, null); radioButton1.setTextColor(0xff2C97D4); } //Set the style of the following three buttons and set them all to gray private void setImg() { radioButton1.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.home_normal), null, null); radioButton2.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.message_normal), null, null); radioButton3.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.my_normal), null, null); radioButton1.setTextColor(0xff979797); radioButton2.setTextColor(0xff979797); radioButton3.setTextColor(0xff979797); } //Here is the monitor button. Press it to give the required page @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { switch (buttonView.getId()) { case R.id.radioButton1: setImg(); currentTab = 0; radioButton1.setTextColor(0xff2C97D4); radioButton1.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.home_selected), null, null); setSelect(0); break; case R.id.radioButton2: if (CommonData.isLogin) { setImg(); currentTab = 1; radioButton2.setTextColor(0xff2C97D4); radioButton2.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.message_selected), null, null); setSelect(1); } else { Intent intent = new Intent(this, LoginActivity.class); startActivityForResult(intent, 1); } break; case R.id.radioButton3: setImg(); currentTab = 2; radioButton3.setTextColor(0xff2C97D4); radioButton3.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.my_selected), null, null); setSelect(2); break; } } } //This is when you first log in, send an ok, and then judge whether to log in to the page. If you log in, you will enter the interface represented by 1 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { String result = data.getExtras().getString("result");// Get new Activity // Data returned after closing if (result.equals("ok")) { setImg(); currentTab = 1; radioButton2.setTextColor(0xff2C97D4); radioButton2.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.message_selected), null, null); setSelect(1); } else { if (currentTab == 0) { radioButton1.setChecked(true); radioButton1.setTextColor(0xff2C97D4); radioButton1.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.home_selected), null, null); setSelect(0); } else if (currentTab == 2) { radioButton3.setChecked(true); radioButton3.setTextColor(0xff2C97D4); radioButton3.setCompoundDrawablesWithIntrinsicBounds( null, getApplication().getResources().getDrawable( R.drawable.my_selected), null, null); setSelect(2); } } } //This method allows the unnecessary content on the interface to be hidden and the required content to be displayed public void setSelect(int i) { FragmentManager fm = getFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); switch (i) { case 0: hideFragment(transaction, twoFragment); hideFragment(transaction, threeFragment); if (oneFragment == null) { oneFragment = new OneFragment(); transaction.add(R.id.fl_content, oneFragment, "oneFragment"); } else { transaction.show(oneFragment); } break; case 1: hideFragment(transaction, oneFragment); hideFragment(transaction, threeFragment); if (twoFragment == null) { twoFragment = new TwoFragment(); transaction.add(R.id.fl_content, twoFragment, "twoFragment"); } else { transaction.show(twoFragment); } break; case 2: hideFragment(transaction, oneFragment); hideFragment(transaction, twoFragment); if (threeFragment == null) { threeFragment = new ThreeFragment(); transaction.add(R.id.fl_content, threeFragment, "threeFragment"); } else { transaction.show(threeFragment); } break; } transaction.commit(); } //Hide fragment private void hideFragment(FragmentTransaction transaction, Fragment fragment) { if (fragment != null) { transaction.hide(fragment); } } /** * Click the exit button to exit the interface without closing. The application does not need to be restarted the next time it enters */ @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { // Specific operation code moveTaskToBack(true); return true; } return super.dispatchKeyEvent(event); } }
III The front-end functions implemented in Android and the back-end requests processed in IDEA
1. Login function (corresponding to LoginActivity and its layout interface and interface processing in IDEA). The following only shows the code of Activity
Experience: in Spring, the mapper layer is usually defined first, and then xml fetches the database and returns the required data. Redefine Service layer, impl rewrite service method, in which mapper layer method is used to remove data. Finally, the controller uses the service method to process the request
1. First create a login interface for Android. The following is a detailed explanation of LoginActivity code
public class LoginActivity extends Activity implements View.OnClickListener { private TextView tv_back, tv_title, tv_register; private EditText et_account, et_password; private Button btn_login; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); initView(); } private void initView() { tv_title = (TextView) findViewById(R.id.tv_title); tv_title.setText(R.string.login); tv_back = (TextView) findViewById(R.id.tv_back); tv_register = (TextView) findViewById(R.id.tv_register); btn_login = (Button) findViewById(R.id.btn_login); tv_back.setOnClickListener(this); tv_register.setOnClickListener(this); btn_login.setOnClickListener(this); et_account = (EditText) findViewById(R.id.et_account); et_password = (EditText) findViewById(R.id.et_password); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tv_register: Intent intent=new Intent(this,RegisterActivity.class); startActivity(intent); break; case R.id.btn_login: String username=et_account.getText().toString(); String psd=et_password.getText().toString(); //Through okhttoutils The get method obtains the json data from the URL, and the json data will be stored in the msg of the onFinish method //The URL here accesses the web address and triggers the request request in the IDEA, which is processed in the UserController in the IDEA OkHttpUtils.get("http://172.21.254.44:8080/portal/user/login.do?username="+username+"&password="+psd, new OkHttpCallback(){ @Override public void onFinish(String status, String msg) { super.onFinish(status, msg); //Parsing msg Looper.prepare(); Gson gson = new Gson(); //Via gson The from method returns the required type of data ServerResponse<User> serverResponse = gson.fromJson(msg, new TypeToken<ServerResponse<User>>(){}.getType()); System.out.println(serverResponse.getData().getId()); if (serverResponse == null) { Toast.makeText(LoginActivity.this,"Username or password incorrect ",Toast.LENGTH_SHORT).show(); }else{ //Forward the obtained value with hashMap static global variable. HashMap<String,Object> hashMap = new HashMap<String,Object>(); hashMap.put("id",serverResponse.getData().getId()); hashMap.put("name",serverResponse.getData().getUsername()); hashMap.put("password",serverResponse.getData().getPassword()); hashMap.put("phone",serverResponse.getData().getPhone()); hashMap.put("major",serverResponse.getData().getIp()); hashMap.put("sex",serverResponse.getData().getQuestion()); hashMap.put("age",serverResponse.getData().getAnswer()); hashMap.put("school",serverResponse.getData().getEmail()); System.out.println(serverResponse.getData().getId()); //Flag login status CommonData.isLogin=true; //Store the obtained data into the global variable of CommonData CommonData.user_hashMap1=hashMap; Intent intent = new Intent(LoginActivity.this,MainActivity.class); intent.putExtra("result", "ok"); setResult(RESULT_OK, intent); startActivity(intent); } Looper.loop(); } }); break; } } }
2. The URL triggers login Do request, which will be processed in IDEA
1. Receive login in UserController in Controller layer Do request
@RestController//Marked as Controller and returned json data @RequestMapping("/portal/")//All requests begin with / portal public class UserController { @Autowired IUserService userService; @Resource IJianzhiService iJianzhiService; @RequestMapping(value = "user/login.do") public ServerResponse login(String username, String password, HttpSession session){ //Call the loginLogic method of userservice of the Service layer to return the data of the User object ServerResponse serverResponse = userService.loginLogic(username,password); if(serverResponse.isSuccess()){ session.setAttribute(Const.CURRENT_USER,serverResponse.getData()); } //return returns data with User object data and status 0 return serverResponse; } }
2. IUserService called by service layer
public interface IUserService { public ServerResponse loginLogic(String username,String password); }
3.impl rewrite IUserService
@Service public class UserService implements IUserService { @Autowired private UserMapper userMapper; @Override public ServerResponse loginLogic(String username,String password){ //step1: non empty judgment of user name and password /** * Null judgment can also be performed through the encapsulation method in commons Lang dependency * The methods are stringutils isBlank,StringUtils. isEmpty */ if(StringUtils.isBlank(username)){ //Return + failure information returned in serverresponse return ServerResponse.createServerResponseByFail (ResponseCode.USERNAME_NOT_EMPTY.getCode() ,ResponseCode.USERNAME_NOT_EMPTY.getMsg()); } if(StringUtils.isBlank(password)){ return ServerResponse.createServerResponseByFail(ResponseCode.PASSWORD_NOT_EMPTY.getCode(),ResponseCode.PASSWORD_NOT_EMPTY.getMsg()); } //Step 2: check whether the user name exists Integer count = userMapper.findByUsername(username); if(count == 0){ return ServerResponse.createServerResponseByFail (ResponseCode.USERNAME_NOT_EXIST.getCode(), ResponseCode.USERNAME_NOT_EXIST.getMsg());} //step3: call the usermapper method to query the user's information according to the user name and password. User user = userMapper.findByUsernameAndPassword(username,password); if(user == null){ return ServerResponse.createServerResponseByFail (ResponseCode.PASSWORD_ERROR.getCode(), ResponseCode.PASSWORD_ERROR.getMsg());} //step4: the returned result corresponds to the following method to obtain the state 0 and the json data carried in the user object return ServerResponse.createServerResponseBySuccess(convert(user)); /*public static <T> ServerResponse createServerResponseBySuccess(T data){ return new ServerResponse(0,data);}*/ } //In addition, the data returned by the encapsulated UserVO object is displayed to the web page, but the key information is not displayed to the front end for people to see. private UserVO convert(User user){ UserVO userVO = new UserVO(); userVO.setId(user.getId()); userVO.setQuestion(user.getQuestion()); userVO.setAnswer(user.getAnswer()); userVO.setUsername(user.getUsername()); userVO.setPassword(user.getPassword()); userVO.setEmail(user.getEmail()); userVO.setPhone(user.getPhone()); userVO.setIp(user.getIp()); userVO.setCreateTime(DateUtil.date2String(user.getCreateTime())); userVO.setUpdateTime(DateUtil.date2String(user.getUpdateTime())); return userVO; } }
4. The userMapper in the mapper layer calls the method
public interface UserMapper { int findByUsername(@Param("username") String username); User findByUsernameAndPassword(@Param("username") String username,@Param("password") String password); }
5.usermapper references usermapper XML to use the database to find data
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--The corresponding mapper Correspondence--> <mapper namespace="com.example.androidtest.dao.UserMapper"> <!--among paramterType For the input data type, resultType Data type for output--> <!--id Corresponding method name--> <select id="findByUsername" parameterType="String" resultType="int"> select count(*) from nite_user where username = #{username} </select> <select id="findByUsernameAndPassword" parameterType="map" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from nite_user where username = #{username} and password = #{password} </select> </mapper>
II registration function
Idea: 1 The Android end establishes a registration page. After clicking the registration button, you can obtain the required information through the instantiation object and give it to the back end with the URL get request. 2 The backend processes URL requests and stores them into the database.
1. Create registeractivity to transfer the registered information to the URL
< E m p t y M a t h B l o c k > <Empty \space Math \space Block> <Empty Math Block>
@SuppressLint("NewApi") public class RegisterActivity extends Activity implements View.OnClickListener { private TextView tv_back, tv_title; private EditText et_phone, et_password, et_re_password,et_name; private Button btn_register; RadioButton rb_nan,rb_nv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); initView(); } private void initView() { tv_title = (TextView) findViewById(R.id.tv_title); tv_title.setText(R.string.register); tv_back = (TextView) findViewById(R.id.tv_back); btn_register = (Button) findViewById(R.id.btn_register); rb_nan = findViewById(R.id.rb_man); rb_nv = findViewById(R.id.rb_woman); tv_back.setOnClickListener(this); btn_register.setOnClickListener(this); et_phone = (EditText) findViewById(R.id.et_phone); et_password = (EditText) findViewById(R.id.et_password); et_re_password = (EditText) findViewById(R.id.et_re_password); et_name = findViewById(R.id.et_name); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tv_back: Intent intent = new Intent(this,LoginActivity.class); startActivity(intent); break; case R.id.btn_register: String name = et_name.getText().toString(); String phone = et_phone.getText().toString(); String psd= et_password.getText().toString(); String psd1 = et_re_password.getText().toString(); if(phone.equals("")||psd.equals("")||psd1.equals("")||name.equals("")){ Toast.makeText(RegisterActivity.this,"Incomplete information", Toast.LENGTH_LONG).show(); }else if(!psd.equals(psd1)){ Toast.makeText(RegisterActivity.this,"Inconsistent passwords", Toast.LENGTH_LONG).show(); }else { //Send the entered name, password and phone number to the URL request, and let the method in UserController in IDEA get and process it OkHttpUtils.get("http://172.21.254.44:8080/portal/user/register.do?username="+name+"&password="+psd+"&phone"+phone, new OkHttpCallback(){ @Override public void onFinish(String status, String msg) { super.onFinish(status, msg); //Parsing msg Gson gson = new Gson(); ServerResponse<User> serverResponse = gson.fromJson(msg, new TypeToken<ServerResponse<User>>(){}.getType()); int status1 = serverResponse.getStatus(); if(status1 == 0){ Looper.prepare(); //The child thread pop-up window needs to be added Toast.makeText(RegisterActivity.this,"login was successful",Toast.LENGTH_SHORT).show(); Looper.loop(); //The child thread pop-up window needs to be added } } }); Intent intent1 = new Intent(RegisterActivity.this,LoginActivity.class); startActivity(intent1); } break; } } //Does the user already exist private boolean isExist(SQLiteDatabase db, String tel) { // DBHelper helper=new DBHelper(this); // db=helper.getReadableDatabase(); String sql = "select * from user_table where tel = '" + tel + "'"; Cursor cursor = db.rawQuery(sql, new String[0]); // db.close(); if (cursor.getCount() != 0) { Toast.makeText(RegisterActivity.this, "User already exists, cannot register again!", Toast.LENGTH_SHORT).show(); cursor.close(); return true; }else{ cursor.close(); return false; } } // Verify phone number public boolean isMobileNumber(String mobiles) { Pattern p = Pattern .compile("^((13[0-9])|(14[5,7])|(15[^4,\\D])|(18[0-9])|(17[0,6,7,8]))\\d{8}$"); Matcher m = p.matcher(mobiles); return m.matches(); } }
2. The URL triggers the register request, and the UserController in IDEA handles the request
@RequestMapping(value = "user/register.do") public ServerResponse register(User user){ return userService.registerLogic(user); }
3. The method in controller is defined in IUserService interface and rewritten with impl
@Override public ServerResponse registerLogic(User user){ //step1: non empty judgment of some columns of data such as user name and password if(user == null){ return ServerResponse.createServerResponseByFail(ResponseCode.PARAMETER_NOT_EMPTY.getCode(),ResponseCode.PARAMETER_NOT_EMPTY.getMsg()); } String username = user.getUsername(); String password = user.getPassword(); String email = user.getEmail(); String question = user.getQuestion(); String answer = user.getAnswer(); String phone = user.getPhone(); if(StringUtils.isBlank(username)){ return ServerResponse.createServerResponseByFail(ResponseCode.USERNAME_NOT_EMPTY.getCode(),ResponseCode.USERNAME_NOT_EMPTY.getMsg()); } if(StringUtils.isBlank(password)){ return ServerResponse.createServerResponseByFail(ResponseCode.PASSWORD_NOT_EMPTY.getCode(),ResponseCode.PASSWORD_NOT_EMPTY.getMsg()); } //Step 2 judge whether the user name exists Integer count = userMapper.findByUsername(username); if(count > 0){ return ServerResponse.createServerResponseByFail(ResponseCode.USERNAME_EXIST.getCode(),ResponseCode.USERNAME_EXIST.getMsg()); } //step3 determines whether the mailbox exists Integer email_count = userMapper.findByEmail(email); if(email_count > 0){ return ServerResponse.createServerResponseByFail(ResponseCode.EMAIL_EXIST.getCode(),ResponseCode.EMAIL_EXIST.getMsg()); } //step4 registration //Encryptible user.setRole(Const.CUSTOM); Integer result = userMapper.insert(user); if(result == 0){ return ServerResponse.createServerResponseByFail(ResponseCode.REGISTER_FAIL.getCode(),ResponseCode.REGISTER_FAIL.getMsg()); } return ServerResponse.createServerResponseBySuccess(); }
4. Define the above methods in the mapper layer interface and use mapper XML lookup data return results
III working function
Because entering LoginActivity login will transfer to MainActivity judgment, and the Fragment interface represented by 0 will be entered by default at the beginning.
1. Enter OneFragment interface
@SuppressLint("NewApi") public class OneFragment extends Fragment implements OnClickListener { private View rootView; private TextView tv_part_job,tv_full_time; private ListView lv_job; private JobAdapter adapter; //Create two hashmap list types to store full-time and part-time data private List<HashMap<String, Object>> part_job_Data; private List<HashMap<String, Object>> full_job_Data; private int job_type=0;//0 represents part-time and 1 represents full-time public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (rootView == null) { rootView = inflater.inflate(R.layout.fragment_one, container, false); } return rootView; } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initData(); initView(); //Entry position details lv_job.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View arg1, int position, long arg3) { Intent intent=new Intent(getActivity(), JobDetailActivity.class); Bundle data = new Bundle(); data.putSerializable("job", (HashMap<String, Object>)adapter.getItemAtPosition(position)); intent.putExtras(data); startActivity(intent); } }); } private void initData(){ part_job_Data=new ArrayList<HashMap<String, Object>>(); full_job_Data=new ArrayList<HashMap<String, Object>>(); //Go to the UserController through the URL and use the findjianzhi method to obtain the part-time data in the database and return it. OkHttpUtils.get("http://172.21.254.44:8080/portal/findjianzhi.do" , new OkHttpCallback() { @Override public void onFinish(String status, String msg) { super.onFinish(status, msg); //Parse data Gson gson = new Gson(); List<Jianzhi> job = gson.fromJson(msg, new TypeToken<List<Jianzhi>>() {}.getType()); //Looper.prepare(); for (int i = 0; i < job.size(); i++) { HashMap<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put("id", job.get(i).getId()); hashMap.put("img", R.drawable.ic_launcher); hashMap.put("name",job.get(i).getPartjobname()); hashMap.put("jobType", "part-time job"); hashMap.put("company", job.get(i).getPartjobcompany()); hashMap.put("time", job.get(i).getPartjobtime()); hashMap.put("salary", job.get(i).getPartjobsalary()); hashMap.put("people", job.get(i).getPartjobpeople()); hashMap.put("address", job.get(i).getPartjobaddress()); hashMap.put("payWay", job.get(i).getPartjobpayway()); part_job_Data.add(hashMap); } //Looper.loop(); } }); //Go to the UserController through the URL and use the findquanzhi method to obtain the part-time data in the database and return it. OkHttpUtils.get("http://172.21.254.44:8080/portal/findquanzhi.do" , new OkHttpCallback() { @Override public void onFinish(String status, String msg) { super.onFinish(status, msg); //Parse data Gson gson = new Gson(); List<Jianzhi> job = gson.fromJson(msg, new TypeToken<List<Jianzhi>>() {}.getType()); //Looper.prepare(); for (int i = 0; i < job.size(); i++) { HashMap<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put("id", job.get(i).getId()); hashMap.put("img", R.drawable.ic_launcher); hashMap.put("name", job.get(i).getPartjobname()); hashMap.put("jobType", "full-time"); hashMap.put("company", job.get(i).getPartjobcompany()); hashMap.put("time", job.get(i).getPartjobtime().toString()); hashMap.put("salary", job.get(i).getPartjobsalary()); hashMap.put("people", job.get(i).getPartjobpeople()); hashMap.put("address", job.get(i).getPartjobaddress()); hashMap.put("payWay", job.get(i).getPartjobpayway()); full_job_Data.add(hashMap); } //Looper.loop(); } }); } private void initView() { tv_part_job=(TextView) rootView.findViewById(R.id.tv_part_job); tv_full_time=(TextView) rootView.findViewById(R.id.tv_full_time); lv_job=(ListView) rootView.findViewById(R.id.lv_job); tv_part_job.setOnClickListener(this); tv_full_time.setOnClickListener(this); //When you first enter OneFragment, first put the part-time information into listview through adapter adapter=new JobAdapter(getActivity(), part_job_Data); lv_job.setAdapter(adapter); } //Switch part-time and full-time information by clicking events @Override public void onClick(View v) { setTextColor(); switch (v.getId()) { case R.id.tv_part_job: tv_part_job.setTextColor(getResources().getColor(R.color.basecolor)); job_type=0; //Use adapter to connect listview with item. adapter=new JobAdapter(getActivity(), part_job_Data); lv_job.setAdapter(adapter); break; case R.id.tv_full_time: tv_full_time.setTextColor(getResources().getColor(R.color.basecolor)); job_type=1; adapter=new JobAdapter(getActivity(), full_job_Data); lv_job.setAdapter(adapter); break; } } //Change the background color of the font public void setTextColor() { tv_part_job.setTextColor(getResources().getColor(R.color.text_color_primary)); tv_full_time.setTextColor(getResources().getColor(R.color.text_color_primary)); } }
2. There are two URL s, which respectively request part-time and full-time requests in UserController
@RequestMapping(value = "findjianzhi.do") public List<Jianzhi> findjianzhi(){ List<Jianzhi> jianzhi = iJianzhiService.FindAll(); return jianzhi; } @RequestMapping(value = "findquanzhi.do") public List<Jianzhi> findquanzhi(){ List<Jianzhi> quanzhi = iJianzhiService.FindQz(); return quanzhi; }
The two service requests invoked in 3.Controller are defined in the corresponding IJianzhiService.
List<Jianzhi> FindAll(); List<Jianzhi> FindQz();
4. Rewrite the above two methods of service in impl
@Override public List<Jianzhi> FindAll() { List<Jianzhi> jianzhi = jianzhiMapper.findbyall(); return jianzhi; } @Override public List<Jianzhi> FindQz() { List<Jianzhi> quanzhi = jianzhiMapper.findbyqz(); return quanzhi; }
The mapper method invoked in 5.impl is defined in JianzhiMapper and passed mapper.. XML return data
List<Jianzhi> findbyall(); List<Jianzhi> findbyqz();
6.mapper.xml connection database return data
<select id="findbyall" resultType="com.example.androidtest.pojo.Jianzhi" parameterType="string"> select id,partjobname,partjobimg,partjobcompany,partjobtime ,partjobsalary,partjobpeople,partjobaddress,partjobpayway from jianzhi </select> <select id="findbyqz" resultType="com.example.androidtest.pojo.Jianzhi" parameterType="string"> select id,partjobname,partjobimg,partjobcompany,partjobtime,partjobsalary,partjobpeople ,partjobaddress,partjobpayway from quanzhi </select>
IV message list
1. The editing TowFragment interface is used to display the message list
@SuppressLint("NewApi") public class TwoFragment extends Fragment implements View.OnClickListener { private View rootView; private TextView tv_start, tv_going, tv_over; private ListView lv_task; private JobAdapter adapter; //Three list s for displaying three messages private List<HashMap<String, Object>> start_Data; private List<HashMap<String, Object>> going_Data; private List<HashMap<String, Object>> over_Data; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (rootView == null) { rootView = inflater .inflate(R.layout.fragment_two, container, false); } return rootView; } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initData(); initView(); lv_task.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { } }); } private void initData(){ start_Data=new ArrayList<HashMap<String,Object>>(); //Employed going_Data=new ArrayList<HashMap<String,Object>>(); //Not employed over_Data=new ArrayList<HashMap<String,Object>>(); //Registered //Call the URL request of different conds and put the three conds into three list s. OkHttpUtils.get("http://172.21.254.44:8080/portal/list. do? Phone = "+ commondata. User_hashmap1. Get (" phone ") +" & cond = hired“ , new OkHttpCallback() { @Override public void onFinish(String status, String msg) { super.onFinish(status, msg); //Parse data Gson gson = new Gson(); List<Jianzhi> job = gson.fromJson(msg, new TypeToken<List<Jianzhi>>() {}.getType()); //Looper.prepare(); if (job.size() > 0) { for (int i = 0; i < job.size(); i++) { HashMap<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put("id", job.get(i).getId()); hashMap.put("img", R.drawable.ic_launcher); hashMap.put("name", job.get(i).getPartjobname()); if (job.get(i).getId() < 100) { hashMap.put("jobType", "part-time job"); } else { hashMap.put("jobType", "full-time"); } hashMap.put("company", job.get(i).getPartjobcompany()); hashMap.put("time", job.get(i).getPartjobtime()); hashMap.put("salary", job.get(i).getPartjobsalary()); hashMap.put("people", job.get(i).getPartjobpeople()); hashMap.put("address", job.get(i).getPartjobaddress()); hashMap.put("payWay", job.get(i).getPartjobpayway()); start_Data.add(hashMap); } //Looper.loop(); } } }); OkHttpUtils.get("http://172.21.254.44:8080/portal/list. do? Phone = "+ commondata. User_hashmap1. Get (" phone ") +" & cond = not employed“ , new OkHttpCallback() { @Override public void onFinish(String status, String msg) { super.onFinish(status, msg); //Parse data Gson gson = new Gson(); List<Jianzhi> job = gson.fromJson(msg, new TypeToken<List<Jianzhi>>() {}.getType()); //Looper.prepare(); if (job.size() > 0) { for (int i = 0; i < job.size(); i++) { HashMap<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put("id", job.get(i).getId()); hashMap.put("img", R.drawable.ic_launcher); hashMap.put("name", job.get(i).getPartjobname()); if (job.get(i).getId() < 100) { hashMap.put("jobType", "part-time job"); } else { hashMap.put("jobType", "full-time"); } hashMap.put("company", job.get(i).getPartjobcompany()); hashMap.put("time", job.get(i).getPartjobtime()); hashMap.put("salary", job.get(i).getPartjobsalary()); hashMap.put("people", job.get(i).getPartjobpeople()); hashMap.put("address", job.get(i).getPartjobaddress()); hashMap.put("payWay", job.get(i).getPartjobpayway()); going_Data.add(hashMap); } //Looper.loop(); } } }); OkHttpUtils.get("http://172.21.254.44:8080/portal/list. do? Phone = "+ commondata. User_hashmap1. Get (" phone ") +" & cond = registered“ , new OkHttpCallback() { @Override public void onFinish(String status, String msg) { super.onFinish(status, msg); //Parse data Gson gson = new Gson(); List<Jianzhi> job = gson.fromJson(msg, new TypeToken<List<Jianzhi>>() {}.getType()); //Looper.prepare(); if (job.size() > 0) { for (int i = 0; i < job.size(); i++) { HashMap<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put("id", job.get(i).getId()); hashMap.put("img", R.drawable.ic_launcher); hashMap.put("name", job.get(i).getPartjobname()); if (job.get(i).getId() < 100) { hashMap.put("jobType", "part-time job"); } else { hashMap.put("jobType", "full-time"); } hashMap.put("company", job.get(i).getPartjobcompany()); hashMap.put("time", job.get(i).getPartjobtime()); hashMap.put("salary", job.get(i).getPartjobsalary()); hashMap.put("people", job.get(i).getPartjobpeople()); hashMap.put("address", job.get(i).getPartjobaddress()); hashMap.put("payWay", job.get(i).getPartjobpayway()); over_Data.add(hashMap); } //Looper.loop(); } } }); } private void initView() { tv_start = (TextView) rootView.findViewById(R.id.tv_start); tv_going = (TextView) rootView.findViewById(R.id.tv_going); tv_over = (TextView) rootView.findViewById(R.id.tv_over); lv_task = (ListView) rootView.findViewById(R.id.lv_task); tv_start.setOnClickListener(this); tv_going.setOnClickListener(this); tv_over.setOnClickListener(this); adapter=new JobAdapter(getActivity(), start_Data); lv_task.setAdapter(adapter); // System.out.println(CommonData.user_hashMap1.get("phone")); } @Override public void onClick(View v) { setTextColor(); switch (v.getId()) { case R.id.tv_start: adapter=new JobAdapter(getActivity(), start_Data); lv_task.setAdapter(adapter); tv_start.setTextColor(getResources().getColor(R.color.basecolor)); break; case R.id.tv_going: adapter=new JobAdapter(getActivity(), going_Data); lv_task.setAdapter(adapter); tv_going.setTextColor(getResources().getColor(R.color.basecolor)); break; case R.id.tv_over: adapter=new JobAdapter(getActivity(), over_Data); lv_task.setAdapter(adapter); tv_over.setTextColor(getResources().getColor(R.color.basecolor)); break; } } //Change the background color of the font public void setTextColor() { tv_start.setTextColor(getResources().getColor(R.color.text_color_primary)); tv_going.setTextColor(getResources().getColor(R.color.text_color_primary)); tv_over.setTextColor(getResources().getColor(R.color.text_color_primary)); } }
2. According to the URL request, receive it in UserController and call the list method for processing
/* Use the findPhCon method to return a list of IDS, then traverse the IDS in the list and find the corresponding work according to the id. */ @RequestMapping(value = "list.do") public List<Jianzhi> list(String phone,String cond){ List<Integer> list1 = iJianzhiService.findbyPhCon(phone,cond); ArrayList<Jianzhi> arrayList = new ArrayList<Jianzhi>(); for(int i=0;i<list1.size();i++){ if(list1.get(i)<100){ Jianzhi jianzhi = iJianzhiService.selectByid(list1.get(i)); arrayList.add(jianzhi); }else{ Jianzhi quanzhi = iJianzhiService.selectByquanzhi(list1.get(i)); arrayList.add(quanzhi); } } return arrayList; }
3. Define findbyPhCon in the service to find the corresponding id according to the phone and cond, and call different findbyid methods according to the size of the id
//Get the id list by phone number and admission information List<Integer> findbyPhCon(String phone,String cond); //Find a part-time job through id Jianzhi selectByid(int id); //Find a full-time job through id Jianzhi selectByquanzhi(int id);
4. Rewrite the above three methods in impl
@Override public List<Integer> findbyPhCon(String phone,String cond) { Userwork userwork = new Userwork(phone,cond); List<Integer> id = jianzhiMapper.findbyPhCon(userwork); return id; } @Override public Jianzhi selectByid(int id) { return jianzhiMapper.selectByid(id) ; } @Override public Jianzhi selectByquanzhi(int id) { return jianzhiMapper.selectByquanzhi(id) ; }
5. Define the above three methods in jianzhimapper
//According to whether the phone is recorded or not, it is used to find the id List<Integer> findbyPhCon(Userwork userwork); //Find a job by id Jianzhi selectByid(int id); Jianzhi selectByquanzhi(int id);
V my function
1. Edit ThreeFragment to display my interface
@SuppressLint("NewApi") public class ThreeFragment extends Fragment implements View.OnClickListener { private View rootView; private TextView tv_person, tv_about, tv_loginout, tv_nickName; private ImageView iv_head; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (rootView == null) { rootView = inflater.inflate(R.layout.fragment_three, container, false); } return rootView; } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initView(); } @Override public void onResume() { // TODO Auto-generated method stub super.onResume(); if (CommonData.isLogin) //If you log in, your name will be displayed tv_nickName.setText(CommonData.user_hashMap1.get("name").toString()); } private void initView() { tv_person = (TextView) rootView.findViewById(R.id.tv_person); tv_about = (TextView) rootView.findViewById(R.id.tv_about); tv_loginout = (TextView) rootView.findViewById(R.id.tv_loginout); tv_nickName = (TextView) rootView.findViewById(R.id.tv_nickName); iv_head=(ImageView)rootView.findViewById(R.id.iv_head); tv_person.setOnClickListener(this); tv_about.setOnClickListener(this); tv_loginout.setOnClickListener(this); iv_head.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_head: if(CommonData.isLogin){ Intent intent = new Intent(getActivity(), PersonActivity.class); startActivity(intent); }else{ Intent intent=new Intent(getActivity(), LoginActivity.class); startActivity(intent); // Toast.makeText(getActivity(), "user has not logged in!", Toast.LENGTH_SHORT).show(); } break; case R.id.tv_person: if(CommonData.isLogin){ Intent intent = new Intent(getActivity(), PersonActivity.class); startActivity(intent); }else{ Toast.makeText(getActivity(), "User has not logged in!", Toast.LENGTH_SHORT).show(); } break; case R.id.tv_about: Intent intent = new Intent(getActivity(), AboutActivity.class); startActivity(intent); break; case R.id.tv_loginout: CommonData.isLogin = false; CommonData.user_hashMap=null; tv_nickName.setText("Not logged in"); Toast.makeText(getActivity(), "Log out!", Toast.LENGTH_SHORT).show(); break; } } }