【问题标题】:json object save only first value in shared prefarancesjson对象只保存共享prefarances中的第一个值
【发布时间】:2018-05-23 06:53:26
【问题描述】:

我,正在开发一个用于求职的安卓应用程序。在这里,我使用 PHP 作为 JSON 响应从服务器获取作业。每个工作都有不同的工作 ID。如果我想申请工作,job iduser 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);


    }

【问题讨论】:

  • “数据库中已存在作业 ID”的内容到底是什么意思?是否涉及任何错误消息?
  • 这里验证用户 ID 和工作 ID 匹配,然后我们不能申请工作。我们只能申请第一份工作。另一个作业传递相同的作业 ID
  • 那么,错误的jobId被发送到服务器了?你试图发现什么错误?您已经发布了很多代码,找到构建请求的部分对您来说应该很容易
  • @Nha Phạm Thị 在下面回复了答案.. 我快要回答了,请帮帮我

标签: php android json


【解决方案1】:

你不能保存JSON对象。但是你可以保存JSON字符串

SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("key_from_json", "String_value_from_json");
 editor.putInt("key_from_json","int_value_from_json");
 editor.commit();

【讨论】:

  • 帮帮我。但在这里我可以保存它。并且只能申请一份工作
  • 制作一个 json 数组,将新的 json 附加到旧的 json 中,保存在 SharedPreferences
  • @Nha Phạm Thị 在下面回复了答案 .. 我快要回答了,请帮帮我
【解决方案2】:

每个键都只有一个值,因此您可以只保存一个键 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();

【讨论】:

  • 这里你提到了名为作业的新数组列表,new Gson().toJson(jobs),我为它传递了一个对象。数组列表或作业
  • ["JFYKj","EDTEE","GRWEJ","CcdfC"] 在这里我得到了答案,但是如何获取单个 id 的
  • List jobs = new Gson().fromJson(dataFromSharePref, new TypeToken>(){}.getType());
  • dataFromSharePref ???这里我将使用哪个对象。你能解释一下完整的代码吗……很紧急。帮帮忙
  • dataFromSharePref 是您从 SharePreference 获得的值
猜你喜欢
  • 2020-04-04
  • 2021-01-08
  • 2015-09-11
  • 2021-12-19
  • 1970-01-01
  • 2017-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多