📜 ⬆️ ⬇️

Programming on Android for a web developer or a quick start for the little ones. Part 3

Greetings

The article is a continuation of part 1 and part 2 that I have begun.

Warning


Important: this lesson is not professional. The author of the lesson is not an expert in programming for the Android platform. I apologize in advance for unwarranted expectations. Since the previous lesson received more positive reviews, I decided to continue.
')

What are you talking about


In the first part I mentioned that the application will be able to log in and display the server data. We realize:
  1. Authorization
  2. Listing of data received from the server

For me, authorization is:


This is what I do in the web application. For the client server, I decided to get by with simulating the session using local storage. Requests to the server, receipt and processing of responses have already been considered in Part 2, we proceed to the storage of the “session”.

Data Preservation with Preferences


SharedPreferences
Values ​​are saved as a pair: name, value. After logging in, we save the data. The next time you open the application, we will not need to re-authorize, just read the recorded data.

Record:

SharedPreferences sPref = getPreferences(MODE_PRIVATE); Editor ed = sPref.edit(); ed.putString(LOGIN,login.getText().toString() ); ed.putString(PASSORD,password.getText().toString() ); ed.commit(); 


Reading:

  SharedPreferences sPref = getPreferences(MODE_PRIVATE); String login = sPref.getString(LOGIN, ""); String password = sPref.getString(PASSORD, ""); 


Reading items to list (RoomsActivity)


Suppose we have successfully passed the authorization and we opened the Activity, which receives a list of chat rooms in the form:

 {"rooms":["room1","room2","room3","room4"]} 


Let's do it:

 //     JSONObject json = new JSONObject(result); //    JSONArray jsa = json.getJSONArray("rooms"); //   ListView roomsLv = (ListView) findViewById(R.id.roomsLv); //     json  String[] StringArray = new String[jsa.length()]; for(int i = 0; i < jsa.length(); i++) { StringArray[i] = jsa.getString(i); } //   ArrayAdapter<String> adapter = new ArrayAdapter<String>(RoomsActivity.this,android.R.layout.simple_list_item_1, StringArray); //    roomsLv.setAdapter(adapter); 


After all, we get a working list. Now we’ll process the click on the list item and transfer the room name to another Activity (RoomSetActivity).

 roomsLv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view,int position, long id) { Intent intent = new Intent(RoomsActivity.this, RoomSetActivity.class); intent.putExtra("roomName", parent.getItemAtPosition(position).toString()); startActivity(intent); } }); 


In RoomSetActivity you can read the name of the room like this:

 String roomName = getIntent().getExtras().getString("roomName"); 


The end.

Source: https://habr.com/ru/post/165641/


All Articles