使用Json解析从String数组填充listview

时间:2016-01-25 13:37:16

标签: java android json listview

我正在尝试创建一个具有listview的活动,它具有edittexts,它显示以前存储的数据,当点击edittexts并编辑它们时,它存储编辑的数据并在列表视图上显示新数据。我使用hashmap来解析json值。你能帮帮我吗?

这是我的代码:

public class AdditionalNutrientGoalsActivity extends ActionBarActivity
{
    private static final String TAG = AdditionalNutrientGoalsActivity.class.getName();

    HashMap<String, Integer> map = new HashMap<String, Integer>();

    private String[] arrText =
        new String[]{"Saturated Fat","Trans fat","polyunsaturated fat","Sodium","Fiber","Monosaturated Fat","Potassium"
                ,"Sugar","Iron","Cholestrol","Calcium","Vitamin C","Vitamin A"}; 
    private String[] arrTemp =
        new String[]{ "00 %","00 %","00 %","38 %","77 %","1049 %","00 %","00 %","38 %"
      ,"77 %","1049 %","77 %","1049 %"};// for now hardcodedvalues
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_additional_nutrient_goals);

    MyListAdapter myListAdapter = new MyListAdapter();
    ListView listView = (ListView) findViewById(R.id.customlist1);
    listView.setAdapter(myListAdapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.e("list view", position + "");
            showDialog(arrText[position]);
            // Toast.makeText(getApplicationContext(),"Saved",Toast.LENGTH_SHORT).show();
        }
    });

    ImageView IVback = (ImageView) findViewById(R.id.back);
    IVback.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AdditionalNutrientGoalsActivity.this.finish();
        }
    });
    GetData getData=new GetData();
    getData.execute();

}

void showDialog(String title)
{
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
        AdditionalNutrientGoalsActivity.this);

    // set title
    alertDialogBuilder.setTitle(title);

    alertDialogBuilder
            .setMessage("Enter in gm/day")
            .setCancelable(false)
            .setPositiveButton("Set", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                    //AdditionalNutrientGoalsActivity.this.finish();
                }
            })
            .setView(new EditText(AdditionalNutrientGoalsActivity.this))
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    dialog.cancel();

                }
            });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();
}

private class MyListAdapter extends BaseAdapter
{

    @Override
    public int getCount() {
        if(arrText != null && arrText.length != 0){
            return arrText.length;
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return arrText[position];
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        String data="";
        //ViewHolder holder = null;
        final ViewHolder holder;
        if (convertView == null) {

            holder = new ViewHolder();
            LayoutInflater inflater = AdditionalNutrientGoalsActivity.this.getLayoutInflater();
            convertView = inflater.inflate(R.layout.custom_additional_nutri, null);
            holder.textView1 = (TextView) convertView.findViewById(R.id.textView45);
            holder.editText1 = (TextView) convertView.findViewById(R.id.textView46);
            data =holder.editText1.getText().toString();

            convertView.setTag(holder);

        } else {

            holder = (ViewHolder) convertView.getTag();
        }

        holder.ref = position;

        holder.textView1.setText(arrText[position]);
        holder.editText1.setText(data);
        holder.editText1.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                          int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
               // arrTemp[holder.ref] = arg0.toString();
                saveData saveData=new saveData();
                saveData.execute();
            }
        });

        return convertView;
    }

    private class ViewHolder {
        TextView textView1;
        TextView editText1;
        int ref;
    }
}

这是我的GetData功能:

    private class GetData extends AsyncTask<String, Void, String>
{
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        ArrayList<NameValuePair> parameters = new ArrayList<>();
        parameters.add(new BasicNameValuePair("username", SharedPref.getData(getApplicationContext(), SharConstants.username)));
        parameters.add(new BasicNameValuePair("password", SharedPref.getData(getApplicationContext(), SharConstants.password)));
        // parameters.add(new BasicNameValuePair("token", SharedPref.getData(getApplicationContext(), SharConstants.token)));
        parameters.add(new BasicNameValuePair("date_time", SharedPref.getData(getApplicationContext(), SharConstants.date_time)));

        GetJsonFromServer getJsonFromServer = new GetJsonFromServer();
        String response = getJsonFromServer.getJson(ApiList.getAdditionalNutrientGoals, "POST", parameters);
        Log.e(TAG, response);
        return response;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        try
        {
            JSONObject jsonObject = new JSONObject(s);
            JSONObject response = jsonObject.getJSONObject("response");
            if(response.getInt("success") == 1)
            {
                JSONObject object= response.getJSONObject("data");
                ArrayList<HashMap<String,Integer>> parameters = new ArrayList<HashMap<String, Integer>>();
                // adding each child node to HashMap key => value
                map.put("id",object.getInt("id"));
                map.put("user_id",object.getInt("user_id"));
                map.put("saturated_fat",object.getInt("saturated_fat"));
                map.put("polyunsaturated_fat",object.getInt("polyunsaturated_fat"));
                map.put("monounsaturated_fat",object.getInt("monounsaturated_fat"));
                map.put("trans_fat",object.getInt("trans_fat"));
                map.put("cholesterol",object.getInt("cholesterol"));
                map.put("sodium",object.getInt("sodium"));
                map.put("potassium",object.getInt("potassium"));
                map.put("fiber", object.getInt("fiber"));
                map.put("sugar", object.getInt("sugar"));
                map.put("Vitamin_A", object.getInt("Vitamin_A"));
                map.put("Vitamin_C", object.getInt("Vitamin_C"));
                map.put("calcium", object.getInt("calcium"));
                map.put("iron", object.getInt("iron"));

                parameters.add(map);
                Log.d("map","map"+" "+parameters);

            }
            else
            {
                Toast.makeText(getApplicationContext(), "Server Error, Try Again Later.", Toast.LENGTH_LONG).show();
            }

        }
        catch(Exception e)
        {
            Log.e(TAG, e.toString());
            Toast.makeText(getApplicationContext(), "Server Error", Toast.LENGTH_LONG).show();
        }
    }

我不知道如何存储数据和获取数据。

0 个答案:

没有答案