javaandroidandroid-sharedpreferences

generate N random 4digit int string & 7char string when user clicks generate button & show all when user clicks show buttonUsing sharedpreferences


N keys and values are randomly generated. I tested the code which generates 4 digit string called keys and 7 character string called values based on the user input N, LB, and UB. Now I want to display keys and values using shared preference. When I run my project it only displays 1 key and value every time. Maybe I am not correctly implementing shared preferences.

This is my code for main_activity.java

package com.rough.problem.problem6;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableRow;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    EditText n,lb,ub;
    Button generate, show, quit;
    String number;
    String generatednum;
    String random_string;
    int length = 7;
    int num,min,max;
    SharedPreferences preferences = getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        n = (EditText) findViewById(R.id.num);
        lb = (EditText) findViewById(R.id.lowerbound);
        ub = (EditText) findViewById(R.id.upperbound);

        generate= (Button) findViewById(R.id.Generate);
        show = (Button) findViewById(R.id.Show);
        quit = (Button) findViewById(R.id.Quit);


        generate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num = Integer.parseInt(n.getText().toString());
                min = Integer.parseInt(lb.getText().toString());
                max = Integer.parseInt(ub.getText().toString());


                for (int i = 1; i <= num; i++) {

                    Random random = new Random();
                    generatednum = String.format("%04d", random.nextInt(max + 1 - min) + min);

                   // Key.append(generatednum + "\n");


                    char[] chars1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
                    StringBuilder sb1 = new StringBuilder();
                    Random random1 = new Random();
                    for (int j = 0; j < length; j++)
                    {
                        char c1 = chars1[random1.nextInt(chars1.length)];
                        sb1.append(c1);
                    }
                    random_string = sb1.toString();

                    //  Value.append(random_string + "\n");


                   // editor.commit();
                }
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("key", generatednum);

                editor.putString("value",random_string);
            }
        });

        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent keyIntent = new Intent(MainActivity.this, key.class);
                MainActivity.this.startActivity(keyIntent);
                startActivity(keyIntent);
            }
        });




    }
}

And the code for key.java where it should display the keys and values generated using shared preference.

    package com.rough.problem.problem6;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

import java.util.Random;

public class key extends AppCompatActivity {
    Button Back;
    TextView Key, Value;
    int n,lb,ub;

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

        Back = (Button) findViewById(R.id.back);
        Key = (TextView) findViewById(R.id.key);
        Value = (TextView) findViewById(R.id.value);
        SharedPreferences preferences=getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
        String key = preferences.getString("key",null);
        String value = preferences.getString("value",null);

        Key.append(key + "\n");
        Value.append(value + "\n");
    }
}

This is my main activity gui

enter image description here

and this is the Key.java activity screenshot

enter image description here

It only displays 1 key and value I need help.


Solution

  • It's only displaying one Key and Value because you're only storing one Key and Value. While your for loop does generate n Keys and Values, your SharedPreferences code is outside of the loop at the end, so only the last generated Key and Value gets stored. Since it looks like you want to store all the Keys in one SharedPreferences String and all the Values in another SharedPreferences String, this can be fixed by adding a couple variables to your Generate button's OnClickListener:

    generate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num = Integer.parseInt(n.getText().toString());
                min = Integer.parseInt(lb.getText().toString());
                max = Integer.parseInt(ub.getText().toString());
    
                // This will be the Key String we store in SharedPrefs
                String keyString = "";
                // This will be the Value String we store in SharedPrefs
                String valueString = "";
    
                for (int i = 1; i <= num; i++) {
    
                    Random random = new Random();
                    generatednum = String.format("%04d", random.nextInt(max + 1 - min) + min);
    
                    // Append the generated Key to the keyString
                    keyString = keyString + generatednum + "\n";
    
                    char[] chars1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
                    StringBuilder sb1 = new StringBuilder();
                    Random random1 = new Random();
                    for (int j = 0; j < length; j++)
                    {
                        char c1 = chars1[random1.nextInt(chars1.length)];
                        sb1.append(c1);
                    }
                    random_string = sb1.toString();
    
                    // Append the generated Value to the valueString
                    valueString = valueString + random_string + "\n";
                }
    
                // Store our keyString and valueString in SharedPrefs
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("key", keyString);
                editor.putString("value", valueString);
                // Don't forget to commit your changes to SharedPrefs!
                editor.commit();
            }
        });