无法在Andorid的“共享首选项”中保存ArrayList值

时间:2019-04-19 04:21:17

标签: java android json sharedpreferences

任何人都可以帮助我我的代码有什么问题吗 无法将ArrayList文档值保存在共享首选项中 在数组列表文档的调试中获取空值

请帮助我

预先感谢

这是我的JSON响应

{
   "errCode": 0,
   "message": "Success",
   "responseDestinationDocument": [
       {
           "name": "United Arab Emirates",
           "document": [
               {
                   "name": "Passport Front",
                   "id": "2",
                   "notes": [
                       {
                           "name": "Upload colored passport copies."
                       },
                       {
                           "name": "Passport should be valid 6 months from the date of entry in Sri Lanka."
                       },
                       {
                           "name": "DDDDDDD"
                       }
                   ]
               },
               {
                   "name": "Passport Back",
                   "id": "3",
                   "notes": [
                       {
                           "name": "Upload colored passport copy."
                       }
                   ]
               },
               {
                   "name": "Photograph",
                   "id": "4",
                   "notes": [
                       {
                           "name": "Upload photograph with white background"
                       }
                   ]
               }
           ]
       }
   ]
}

我想将ArrayList文档值保存在共享首选项中

这是活动代码

  public class UploadDocumentsActivity extends AppCompatActivity {


    private MyCustomAdapter myCustomAdapter;
    protected ViewDialog viewDialog;
    String destination_id, start_date, end_date, no_of_travellers, destination_name, package_id, radioSexButton, booking_id, count_index;
    private List<ResponseBookingDocument> responseBookingDocumentArrayList;
    private List<Document> document1ArrayList;
    Document document1;
    private RecyclerView recyclerView_Identity;
    private static final int SELECT_PICTURE = 100;
    private static final int STORAGE_PERMISSION_CODE = 123;

    final Handler handler = new Handler();
    final int delay = 1000; //milliseconds
    private ImageView imageView1;
    String selectedImagePath;
    private Uri filePath_1;
    private boolean isOnTag = false;
    Bitmap bitmap;
   preivate ArrayList<String> nameList = new ArrayList<>();
   preivate ArrayList<String> idList = new ArrayList<>();


    TextView continueTextView;
    private Runnable mToast = new Runnable() {
        @Override
        public void run() {
//            documentRequiredCall();
            handler.postDelayed(this, 1000);
        }
    };

    ResponseBookInfo responseBookInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_documents);
        viewDialog = new ViewDialog(this);
        viewDialog.setCancelable(false);


//        Log.e("document1", document1.getId() + "");

        try {

            document1 = PrefUtils.getDocId(UploadDocumentsActivity.this);

            Log.e("document1", document1.getId() + "");

        } catch (Exception e) {
            e.printStackTrace();
        }
        Intent i = getIntent();

        destination_id = i.getStringExtra("destination_id");
        package_id = i.getStringExtra("package_id");
        radioSexButton = i.getStringExtra("radioSexButton");
        booking_id = i.getStringExtra("booking_id");
        count_index = i.getStringExtra("count_index");
        Log.e("BookING", booking_id + "");
        destination_name = i.getStringExtra("destination_name");

        start_date = i.getStringExtra("start_date");
        end_date = i.getStringExtra("end_date");
        no_of_travellers = i.getStringExtra("no_of_travellers");
        recyclerView_Identity = findViewById(R.id.recyclerView_Identity);
        continueTextView = findViewById(R.id.continueTextView);


        LinearLayoutManager layoutManager = new LinearLayoutManager(UploadDocumentsActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView_Identity.setLayoutManager(layoutManager);
        recyclerView_Identity.setHasFixedSize(true);

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

                Intent i = new Intent(UploadDocumentsActivity.this, ApplicationFormActivity.class);
                i.putExtra("booking_id", booking_id);
                i.putExtra("count_index", count_index);
                i.putExtra("start_date", start_date);
                i.putExtra("end_date", end_date);

                startActivity(i);

            }
        });

        documentRequiredCall();

//

        Log.e("Values", destination_id + " " + package_id + " " + end_date + " " + no_of_travellers + "  " + count_index + "");
    }

    public void documentRequiredCall() {

        Call<DocumentFetchModel> call = RetrofitClient
                .getInstance().getApi().documentFetchModel(booking_id, count_index);

        showProgressDialog();
        call.enqueue(new Callback<DocumentFetchModel>() {

            @Override
            public void onResponse(Call<DocumentFetchModel> call, retrofit2.Response<DocumentFetchModel> response) {
                final DocumentFetchModel documentFetchModel = response.body();
                hideProgressDialog();


                PrefUtils.setDocId(documentFetchModel.getResponseBookingDocument().get(0).getDocument(), UploadDocumentsActivity.this);

int size = documentFetchModel.getResponseBookingDocument().get(0).getDocument().size();
for (int i = 0; i < size; i++) {
            nameList.add(documentFetchModel.getResponseBookingDocument().get(0).getDocument().get(i).getName());
idList.add(documentFetchModel.getResponseBookingDocument().get(0).getDocument().get(i).getId());
        }


//here is app preference class saving the values
AppPreference.setNameList(this, nameList);
 AppPreference.setIdList(this, idLIst);

                if (documentFetchModel.getErrCode().booleanValue() == true) {

                    responseBookingDocumentArrayList = new ArrayList<ResponseBookingDocument>();


                    try {

                        Log.e("Booking_Document", new Gson().toJson(response.body()));
                        document1ArrayList = documentFetchModel.getResponseBookingDocument().get(0).getDocument();

                        myCustomAdapter = new MyCustomAdapter(document1ArrayList);
                        recyclerView_Identity.setAdapter(myCustomAdapter);
                        myCustomAdapter.notifyDataSetChanged();


                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                } else {

                    Toast.makeText(UploadDocumentsActivity.this, documentFetchModel.getMessage() + "", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<DocumentFetchModel> call, Throwable t) {

                hideProgressDialog();
                Toast.makeText(UploadDocumentsActivity.this, t.getMessage() + "", Toast.LENGTH_LONG).show();
                Log.e("Error", t.getMessage() + "");
            }
        });


    }

    protected void hideProgressDialog() {
        viewDialog.dismiss();
    }

    protected void showProgressDialog() {
        viewDialog.show();
    }

    protected void showProgressDialog(String message) {
        showProgressDialog();
    }



    public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.MyViewHolder> {

        private List<Document> moviesList;

        public class MyViewHolder extends RecyclerView.ViewHolder {
            public TextView textTitle;
            public ImageView imageUpload, imageFetch;

            private List<Note> noteArrayList;
            private MyCustomAdapter2 myCustomAdapter2;
            private RecyclerView recyclerView_Identity_Bullets;

            public MyViewHolder(View view) {
                super(view);

                textTitle = view.findViewById(R.id.textTitle);
                imageUpload = view.findViewById(R.id.imageUpload);
                imageFetch = view.findViewById(R.id.imageFetch);

                recyclerView_Identity_Bullets = view.findViewById(R.id.recyclerView_Identity_Bullets);

                LinearLayoutManager layoutManager2 = new LinearLayoutManager(UploadDocumentsActivity.this);
                layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
                recyclerView_Identity_Bullets.setLayoutManager(layoutManager2);
                recyclerView_Identity_Bullets.setHasFixedSize(true);


            }

        }


        public MyCustomAdapter(List<Document> moviesList) {
            this.moviesList = moviesList;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_upload_document, parent, false);

            return new MyCustomAdapter.MyViewHolder(itemView);
        }

        public void clear() {
            int size = this.moviesList.size();
            if (size > 0) {
                for (int i = 0; i < size; i++) {
                    this.moviesList.remove(0);
                }

                this.notifyItemRangeRemoved(0, size);
            }
        }

        @Override
        public void onBindViewHolder(final MyViewHolder holder, final int position) {


            final Document datum = moviesList.get(position);


            holder.textTitle.setText(datum.getName() + "");

            holder.noteArrayList = datum.getNotes();
            holder.myCustomAdapter2 = new MyCustomAdapter2(holder.noteArrayList);
            holder.recyclerView_Identity_Bullets.setAdapter(holder.myCustomAdapter2);


            if (datum.getImageName().equals("")) {
                holder.imageFetch.setVisibility(View.GONE);
                holder.imageUpload.setVisibility(View.VISIBLE);

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

                        Toast.makeText(UploadDocumentsActivity.this, datum.getId(), Toast.LENGTH_SHORT).show();

                    }
                });


            } else {

                holder.imageUpload.setVisibility(View.GONE);
                holder.imageFetch.setVisibility(View.VISIBLE);
                Picasso.with(UploadDocumentsActivity.this).load(datum.getImageName() + "").into(holder.imageFetch);


            }


        }

        @Override
        public int getItemCount() {
            return moviesList.size();
        }

    }

    public class MyCustomAdapter2 extends RecyclerView.Adapter<MyCustomAdapter2.MyViewHolder> {

        private List<Note> moviesList;

        public class MyViewHolder extends RecyclerView.ViewHolder {
            public TextView textBullet;


            public MyViewHolder(View view) {
                super(view);

                textBullet = view.findViewById(R.id.textBullet);

            }

        }


        public MyCustomAdapter2(List<Note> moviesList) {
            this.moviesList = moviesList;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_upload_bullets_and_image, parent, false);

            return new MyViewHolder(itemView);
        }

        public void clear() {
            int size = this.moviesList.size();
            if (size > 0) {
                for (int i = 0; i < size; i++) {
                    this.moviesList.remove(0);
                }

                this.notifyItemRangeRemoved(0, size);
            }
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, final int position) {


            final Note datum = moviesList.get(position);


            holder.textBullet.setText(" \u25CF " + datum.getName() + "");

            Log.e("textBullet", datum.getName() + "");


        }

        @Override
        public int getItemCount() {
            return moviesList.size();
        }

    }

    @Override
    public void onStart() {
        super.onStart();
        mToast.run();
    }

    @Override
    public void onStop() {
        super.onStop();
        handler.removeCallbacks(mToast);
    }

}

这是模型课

public class DocumentFetchModel {

    @SerializedName("errCode")
    @Expose
    private Boolean errCode;
    @SerializedName("message")
    @Expose
    private String message;
    @SerializedName("responseBookingDocument")
    @Expose
    private List<ResponseBookingDocument> responseBookingDocument = null;

    public Boolean getErrCode() {
        return errCode;
    }

    public void setErrCode(Boolean errCode) {
        this.errCode = errCode;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public List<ResponseBookingDocument> getResponseBookingDocument() {
        return responseBookingDocument;
    }

    public void setResponseBookingDocument(List<ResponseBookingDocument> responseBookingDocument) {
        this.responseBookingDocument = responseBookingDocument;
    }
}


public class ResponseBookingDocument {

    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("document")
    @Expose
    private List<Document> document = null;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Document> getDocument() {
        return document;
    }

    public void setDocument(List<Document> document) {
        this.document = document;
    }

}

公共类DocumentFetchModel {

   @SerializedName("errCode")
    @Expose
    private Boolean errCode;
    @SerializedName("message")
    @Expose
    private String message;
    @SerializedName("responseBookingDocument")
    @Expose
    private List<ResponseBookingDocument> responseBookingDocument = null;

    public Boolean getErrCode() {
        return errCode;
    }

    public void setErrCode(Boolean errCode) {
        this.errCode = errCode;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public List<ResponseBookingDocument> getResponseBookingDocument() {
        return responseBookingDocument;
    }

    public void setResponseBookingDocument(List<ResponseBookingDocument> responseBookingDocument) {
        this.responseBookingDocument = responseBookingDocument;
    }
}

这是ComplexPreference

public class ComplexPreferences {

    private static ComplexPreferences complexPreferences;
    private Context context;
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    private static Gson GSON = new Gson();
    Type typeOfObject = new TypeToken<Object>() {
    }.getType();

    private ComplexPreferences(Context context, String namePreferences, int mode) {
        this.context = context;
        if (namePreferences == null || namePreferences.equals("")) {
            namePreferences = "complex_preferences";
        }
        preferences = context.getSharedPreferences(namePreferences, mode);
        editor = preferences.edit();
    }

    public static ComplexPreferences getComplexPreferences(Context context,
                                                           String namePreferences, int mode) {

//      if (complexPreferences == null) {
        complexPreferences = new ComplexPreferences(context,
                namePreferences, mode);
//      }

        return complexPreferences;
    }

    public void putObject(String key, Object object) {
        if(object == null){
            throw new IllegalArgumentException("object is null");
        }

        if(key.equals("") || key == null){
            throw new IllegalArgumentException("key is empty or null");
        }

        editor.putString(key, GSON.toJson(object));
    }

    public void commit() {
        editor.commit();
    }

    public void clearObject() {
        editor.clear();
    }

    public <T> T getObject(String key, Class<T> a) {

        String gson = preferences.getString(key, null);
        if (gson == null) {
            return null;
        } else {
            try{
                return GSON.fromJson(gson, a);
            } catch (Exception e) {
                throw new IllegalArgumentException("Object storaged with key " + key + " is instanceof other class");
            }
        }
    }


}

这里是PrefUtils类

public class PrefUtils {
  public static DocumentFetchModel getDoc(Context ctx) {
        ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(ctx, "get_doc", 0);
        DocumentFetchModel currentUser = complexPreferences.getObject("docs", DocumentFetchModel.class);
        return currentUser;
    }

    public static void setDoc(DocumentFetchModel currentUser, Context ctx) {
        ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(ctx, "get_doc", 0);
        complexPreferences.putObject("docs", currentUser);
        complexPreferences.commit();
    }

    }

1 个答案:

答案 0 :(得分:0)

您可以像这样将列表保存在sharedpreference中:-

    public class AppPreferences {
                private static SharedPreferences mPrefs;
                private static SharedPreferences.Editor mPrefsEditor;

                public static Set<String> getName(Context ctx) {
    mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    return mPrefs.getStringSet("nameList", null);
}

public static void setName(Context ctx, ArrayList<String> value) {
    mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    mPrefsEditor = mPrefs.edit();
    Set<String> set = new HashSet<>();
    set.addAll(value);
    mPrefsEditor.putStringSet("nameList", set);
    mPrefsEditor.commit();
}
        }

设置列表:-

setCamEval(activity, list);

获取列表:-

getCamEval(this);