首页 > 解决方案 > json对象只保存共享prefarances中的第一个值

问题描述

我正在开发一个用于求职的安卓应用程序。在这里,我使用 PHP 作为 JSON 响应从服务器获取作业。每个工作都有不同的工作ID。如果我想申请工作,job id并发user id送到 PHP MySQL 数据库。但是这里的每个工作申请都只通过一个job id。所以我不能申请另一份工作,因为job id已经在数据库中。那么如何在共享首选项中保存 json 对象以及如何检索它。请帮我。帮助将不胜感激...

模型类

public class getData {
    public String job_title = "";
    public String job_description = "";
    public String address = "";
    public String job_type="";
    public String city="";
    public String job_id="";

    public String getJob_description() {
        return job_description;
    }

    public void setJob_description(String job_description) {
        this.job_description = job_description;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getJob_type() {
        return job_type;
    }

    public void setJob_type(String job_type) {
        this.job_type = job_type;
    }

    public String getJob_title() {
        return job_title;
    }

    public void setJob_title(String job_title) {
        this.job_title = job_title;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getJob_id() {
        return job_id;
    }

    public void setJob_id(String job_id) {
        this.job_id = job_id;
    }
}

控制器类

public class ParserCard extends AsyncTask<Void, Integer, Integer> {
    Context c;
    String data;
    SwipeDeck swipeDeck;
    ProgressDialog pd;
    ArrayList<getData> arrayList = new ArrayList<getData>();
    private SwipeDeckAdapter adapter;

    public  static String job;

    public ParserCard(Context c, String data, SwipeDeck swipeDeck) {
        this.c = c;
        this.data = data;
        this.swipeDeck = swipeDeck;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = new ProgressDialog(c);
        pd.setTitle("Parser");
        pd.setMessage("Parsing....");
        pd.show();
    }

    @Override
    protected Integer doInBackground(Void... params) {
        return this.parse();
    }

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
        pd.dismiss();
        if(integer == 1){
            adapter = new SwipeDeckAdapter(arrayList, c);
            swipeDeck.setAdapter(adapter);
            //Toast.makeText(c, arrayList.size()+"", Toast.LENGTH_LONG).show();
        }else {
            Toast.makeText(c, "Unable to get data from server", Toast.LENGTH_LONG).show();
        }

    }
    private int parse(){
        try {

              JSONArray jsonArray = new JSONArray(data);

            arrayList.clear();
            for (int i = 0; i<jsonArray.length(); i++){
                getData pd = new getData();
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                pd.setJob_title(jsonObject.getString("job_title"));
                pd.setJob_type(jsonObject.getString("job_type"));
                pd.setJob_description(jsonObject.getString("job_description"));
                pd.setAddress(jsonObject.getString("address"));
                pd.setCity(jsonObject.getString("city"));

                pd.setJob_id(jsonObject.getString("job_id"));
                job=jsonObject.getString("job_id");

                SharedPreferences.Editor editor = c.getSharedPreferences(Config.SHARED_PREF_NAME, MODE_PRIVATE).edit();
                editor.putString("jobId", job);

                editor.commit();

                arrayList.add(pd);

            }
            return 1;
        } catch (JSONException e) {
            Log.e("sopheak", e.toString());
            e.printStackTrace();
        }
        return 0;
    }
}

适配器类

public class SwipeDeckAdapter extends BaseAdapter {

    private ArrayList<getData> data;
    private Context context;
    LayoutInflater mInflater;

    public SwipeDeckAdapter(ArrayList<getData> data, Context context) {
        this.data = data;
        this.context = context;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        mInflater = LayoutInflater.from(context);
        View v = convertView;
        if (v == null) {
            v = mInflater.inflate(R.layout.cardview, null);
        }
        getData pd = new getData();
       // ImageView imageView = (ImageView) v.findViewById(R.id.offer_image);
        TextView tv_title = (TextView)v.findViewById(R.id.cardviewjobheading);
        TextView tv_description= (TextView)v.findViewById(R.id.cardviewJobDescription);
        TextView tv_jobtype = (TextView)v.findViewById(R.id.cardviewJobTime);
        TextView tv_companyadress = (TextView)v.findViewById(R.id.cardviewcompanyname);
        TextView tv_companycity = (TextView)v.findViewById(R.id.cardviewcompanyaddress);
        TextView tv_jobid=(TextView)v.findViewById(R.id.cardviewjobid);
        tv_title .setText(data.get(position).getJob_title().toString());
        tv_jobtype.setText(data.get(position).getJob_type().toString());
        tv_description.setText(data.get(position).getJob_description().toString());
        tv_companyadress.setText(data.get(position).getAddress().toString());
        tv_companycity.setText(data.get(position).getCity().toString());
        tv_jobid.setText(data.get(position).getJob_id().toString());


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

            }
        });
        return v;
    }
}

主要活动

public class MainActivity extends AppCompatActivity {
    private SwipeDeck cardStack;

    private ProgressDialog pDialog;
    RequestQueue requestQueue;

    String jobid;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tindercard);
        //FOR ACTION BAR
        ActionBar actionBar = getSupportActionBar();
        //GET BG IMAGE AS BITMAP
        BitmapDrawable background = new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.toolbar));
        //SET BG
        actionBar.setBackgroundDrawable(background);
        // getSupportActionBar().hide();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        cardStack = (SwipeDeck)findViewById(R.id.swipe_deck);
        ImageButton btn2 = (ImageButton)findViewById(R.id.rejectBtn);
        ImageButton btn = (ImageButton)findViewById(R.id.acceptBtn);
        cardStack.setHardwareAccelerationEnabled(true);

        String titles  = getIntent().getExtras().getString("title");
        String locations = getIntent().getExtras().getString("location");


        String urlData = "https://alot.ae/api/joblist.php?job_title="+titles+"&city="+locations;

        urlData = urlData.replaceAll(" ", "%20");

        final DownloaderCard dl = new DownloaderCard(MainActivity.this,urlData , cardStack);
        dl.execute();
        cardStack.setEventCallback(new SwipeDeck.SwipeEventCallback() {
            @Override
            public void cardSwipedLeft(int position) {
                // Log.i("MainActivity", "card was swiped left, position in adapter: " + position);
            }

            @Override
            public void cardSwipedRight(int position) {

                saveinformation();



            }

            @Override
            public void cardsDepleted() {

                MaterialToast materialToast=new MaterialToast(MainActivity.this);
                materialToast.show("No Jobs Available", ContextCompat.getDrawable(MainActivity.this,R.drawable.toast_drawable),
                        ContextCompat.getColor(MainActivity.this,R.color.colorAccent),
                        Gravity.CENTER_HORIZONTAL);
            }

            @Override
            public void cardActionDown() {
                // Log.i(TAG, "cardActionDown");
            }

            @Override
            public void cardActionUp() {
                // Log.i, "cardActionUp");
            }

        });
        cardStack.setLeftImage(R.id.left_image);
        cardStack.setRightImage(R.id.right_image);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cardStack.swipeTopCardLeft(180);

            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cardStack.swipeTopCardRight(180);
            }
        });
    }


    private void saveinformation() {







        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();


        StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.URL_APPLYJOB,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String ServerResponse) {

                        // Hiding the progress dialog after all task complete.
                        pDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(ServerResponse);


                            if (jsonObject.getInt("success") == 0) {

                                Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();

                            } else if (jsonObject.getInt("success") == 1) {
                               // Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();
                                MaterialToast materialToast=new MaterialToast(MainActivity.this);
                                materialToast.show(jsonObject.getString("message"), ContextCompat.getDrawable(MainActivity.this,R.drawable.toast_drawable),
                                        ContextCompat.getColor(MainActivity.this,R.color.colorAccent),
                                        Gravity.CENTER_HORIZONTAL);
                                } else

                                Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {


                        pDialog.dismiss();


                        MaterialToast materialToast=new MaterialToast(MainActivity.this);
                        materialToast.show("Check Internet Connection", ContextCompat.getDrawable(MainActivity.this,R.drawable.toast_drawable),
                                ContextCompat.getColor(MainActivity.this,R.color.colorAccent),
                                Gravity.CENTER_HORIZONTAL);
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {

                // Creating Map String Params.
                Map<String, String> params = new HashMap<String, String>();

                // Adding All values to Params.
                SharedPreferences prefs = getApplicationContext().getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
                String userid = prefs.getString("userId","");
                String jobid =  prefs.getString("jobId","");



                params.put("user_id",userid);
                params.put("job_id",jobid);

                return params;
            }

        };


        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);


    }

标签: phpandroidjson

解决方案


每个键只有一个值,因此您可以job_id只保存一个带有值的键。如果要保存多个作业,则应保存为列表。例子:

List<String> jobs = new ArrayList<>(); 
        for (int i = 0; i<jsonArray.length(); i++){
            getData pd = new getData();
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            pd.setJob_title(jsonObject.getString("job_title"));
            pd.setJob_type(jsonObject.getString("job_type"));
            pd.setJob_description(jsonObject.getString("job_description"));
            pd.setAddress(jsonObject.getString("address"));
            pd.setCity(jsonObject.getString("city"));

            pd.setJob_id(jsonObject.getString("job_id"));
            jobs.add(jsonObject.getString("job_id"));


            arrayList.add(pd);

        }

 SharedPreferences.Editor editor = c.getSharedPreferences(Config.SHARED_PREF_NAME, MODE_PRIVATE).edit();
            editor.putString("jobId", new Gson().toJson(jobs));
            // you should use Gson lib to convert string to object and object to string
            editor.commit();

推荐阅读