简体   繁体   中英

Retrieve data from server and send it to next activity

I retrieve the data from server using php, I want send it to next activity

I already retrieve the id and name, How can I store it and send to next activity

This is my list view


private void loadIntoListView(String json) throws JSONException {
        JSONArray jsonArray = new JSONArray(json);
        String[] viewstudent= new String[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            viewstudent[i] = obj.getString("id") + " " + obj.getString("name");

           //is here store it for send to next activity?

        }
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, viewstudent);
        lv.setAdapter(arrayAdapter);

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {


               //I think here maybe send data to next activity
                
            }


        });

Have any simple way? Can give me some example?

You can parse data json by use Gson and create Java class from jsonschema2pojo.org.

To send data to next activiy, you can use Bundle.

You should use SharedPreferences to save simple data types like

String, Integer, Boolean, Long, Short, ...

To send data to another activity you use bundle.

  • Shared Preferences To Store Data
  1. To get shared preferences:
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
  1. Store data to Shared Preferences:
prefs.edit().putLong("Id_KEY", myUserId).apply();
  1. To read data from Shared Preferences
int userId = prefs.getInt("Id_KEY", -1);
  • Bundles to send data to another activity
  1. Send data to SecondActivity from FirstActivity
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
        intent.putExtra("ACTIVITY_ID_KEY", myUserId);
        startActivity(intent
    );
  1. Receive Data from FirstActivity:
overide void onCreate(...) {
   ...
   Intent intent = getIntent();
   String userId = intent.getStringExtra("ACTIVITY_ID_KEY", -1);
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM