简体   繁体   中英

Save Arraylist in Android Studio (Gson, or Storage)

I am developing a tool that scans for hosts on the local network. This works, it then adds it to an arraylist and displays it. (It looks like this: https://gyazo.com/fe212f1705ea2be35f922625017addb7 )

I would like to know how to add the functionality to save this arraylist (named: ipList). I am not sure what to use, GSON or to a txt file and save it to internal or external storage, either way is fine by me but ideally I would like to load this file (the saved list) from another activity.

Here is my code:

private Button btnScan;
private ListView listViewIp;
ArrayList<String> ipList;
ArrayAdapter<String> adapter;


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

    mTextMessage = (TextView) findViewById(R.id.message);
    BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
    navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);



    btnScan = (Button)findViewById(R.id.scan);
    listViewIp = (ListView)findViewById(R.id.listviewip);


    ipList = new ArrayList<>();
    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, android.R.id.text1, ipList);
    listViewIp.setAdapter(adapter);

        final Gson gson = new Gson();

        final String json = gson.toJson(ipList);

    btnScan.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new ScanIpTask().execute();

            listViewIp.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    switch (position){
                        case 0:
                            Intent intent = new Intent(Homepage.this, Details.class);
                            startActivity(intent);
                            break;
                        case 1:
                           // ipList.remove(1);
                          //  Intent banaan = new Intent(Homepage.this, Register.class);
                          //  startActivity(banaan);
                            Toast.makeText(getApplicationContext(), "Banan" + ipList.size(), Toast.LENGTH_SHORT).show();
                        case 3:


                            Toast.makeText(getApplicationContext(), json, Toast.LENGTH_SHORT).show();
                            break;

                    }


                }
            });
        }


    });}

String ip = "";
String subnet = "10.0.2.";

private String getSubnetAddress(int address)
{
    String ipString = String.format(
            "%d.%d.%d",
            (address & 0xff),
            (address >> 8 & 0xff),
            (address >> 16 & 0xff));

    return ipString;
}

class ScanIpTask extends AsyncTask<Void, String, Void>{




    /*
    Scan IP 192.168.1.100~192.168.1.110
    you should try different timeout for your network/devices
     */
    // static final String subnet = "10.0.2.";
    static final int lower = 0;
    static final int upper = 254;
    static final int timeout = 50;

    @Override
    protected void onPreExecute() {
        ipList.clear();
        adapter.notifyDataSetInvalidated();
        Toast.makeText(Homepage.this, "Scan IP...", Toast.LENGTH_LONG).show();
    }

    @Override
    protected Void doInBackground(Void... params) {

        for (int i = lower; i <= upper; i++) {
            String host = subnet + i;

            try {
                InetAddress inetAddress = InetAddress.getByName(host);
                if (inetAddress.isReachable(timeout)){
                    publishProgress(inetAddress.toString().split("/")[1]);
                }

            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        ipList.add(values[0]);
        adapter.notifyDataSetInvalidated();
        Toast.makeText(Homepage.this, values[0], Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        Toast.makeText(Homepage.this, "Done", Toast.LENGTH_LONG).show();
    }
}

So I tried saving the arraylist, named ipList to GSON but I honestly dont know how to do it.

EDIT

I have added the following two classes to save and load the data and I added a save button for it.

   private void saveData(){
         SharedPreferences sharedpreferences = getSharedPreferences("Shared 
  Preferences", MODE_PRIVATE);
         SharedPreferences.Editor editor =sharedpreferences.edit();
    Gson gson = new Gson();
    String json = gson.toJson(ipList);
    editor.putString("task list", json);
    editor.apply();
    Toast.makeText(Homepage.this, "Saved...", Toast.LENGTH_LONG).show();

}

private void loadData(){
    Toast.makeText(Homepage.this, "Banaan...", Toast.LENGTH_LONG).show();
    SharedPreferences sharedpreferences = getSharedPreferences("Shared Preferences", MODE_PRIVATE);
    Gson gson = new Gson();
    String json = sharedpreferences.getString("task list", null);
    Type type = new TypeToken<ArrayList<String>>(){}.getType();
    ipList = gson.fromJson(json, type);
    if(ipList == null){
        ipList = new ArrayList<>();

    }
}

Something goes wrong when loading the data I think it has to do with this line: Type type = new TypeToken>(){}.getType();

Any tips?

I guess the the "another activity" is in the same project/app.

So, why don't you use SharedPreferences. You can keep all hosts(ips) there. A sample code can be found everywhere. I hope this small hint will help you on the way.

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