使用来自服务器

时间:2015-09-15 06:25:44

标签: android

我是android新手。我正在开发一个应用程序,我以JSONArray格式从服务器获取数据。我将数据保存在共享首选项中,然后检索它并在ListView中显示它。我必须从服务器添加新输入的数据并替换现有数据。我尝试了但是我得到了两次添加的数据,即从共享首选项中检索到的数据,然后是服务器中的数据。

public class TipsActivity extends AppCompatActivity {
     private Toolbar toolbar;
     Pojo pojo;
     ListView listTips;
     String strServerResponse = null;
     ArrayList<Pojo> tips;
     ConnectionDetector cd;
     TipsAdapter tipsAdapter;
     SharedPreferences MyPrefs;
     String tipsss;
     Context context;
     ArrayList<String> tii;
     ProgressBar nPregress;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_tips);
          toolbar = (Toolbar) findViewById(R.id.app_bar);
          toolbar.setTitle("Tip of the Day");
          setSupportActionBar(toolbar);
          listTips = (ListView) findViewById(R.id.tipsList);
          getSupportActionBar().setDisplayHomeAsUpEnabled(true);
          nPregress = (ProgressBar) findViewById(R.id.toolbar_progress_bar);
          nPregress.setVisibility(View.GONE);
          tips = new ArrayList<Pojo>();
          tii = new ArrayList<String>();
          SharedPreferences prefs = getSharedPreferences("MyPref", MODE_PRIVATE);
          Set<String> set = prefs.getStringSet("tipoftheday", null);
          if(set!= null){

          for(String p : set)
          {
              pojo = new Pojo();
              pojo.setTip(p);
              tips.add(pojo);
          }
          tipsAdapter = new TipsAdapter(TipsActivity.this, tips);
          listTips.setAdapter(tipsAdapter);


      }
      else{
         new NetCheck().execute();
    }

    new NetCheck().execute();
   }

private class NetCheck extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        nPregress.setVisibility(View.VISIBLE);
  }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        nPregress.setVisibility(View.GONE);
        SharedPreferences prefs = getSharedPreferences("MyPref", MODE_PRIVATE);
        Set<String> set = prefs.getStringSet("tipoftheday", null);
        for(String p : set)
        {
            pojo = new Pojo();
            pojo.setTip(p);
            tips.add(pojo);
        }
        tipsAdapter = new TipsAdapter(TipsActivity.this, tips);
        listTips.setAdapter(tipsAdapter);

        return;
    }

  @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub

        try {
            HttpClient httpClient = new DefaultHttpClient();

            HttpPost httpRequest = new HttpPost(
                    "http://tipseducation.com/system/eadmin/gettipofday/");

            httpRequest.setHeader("Content-Type", "application/json");

            JSONObject json = new JSONObject();

            StringEntity se = new StringEntity(json.toString());

            se.setContentEncoding("UTF-8");
            se.setContentType("application/json");

            httpRequest.setEntity(se);
            HttpResponse httpRes = httpClient.execute(httpRequest);

            java.io.InputStream inputStream = httpRes.getEntity()
                    .getContent();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream);
            BufferedReader reader = new BufferedReader(inputStreamReader);
            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            inputStream.close();
            strServerResponse = sb.toString();

            Log.e("Server Response", "" + strServerResponse.toString());

            if (strServerResponse != null) {
                try {

                    JSONArray arr = new JSONArray(strServerResponse);
                    JSONObject jsonObj = arr.getJSONObject(0);
                    ArrayList<String> tii = new ArrayList<String>();
                    for (int i = 0; i < arr.length(); i++) {
                        pojo = new Pojo();
                        JSONObject jobj2 = arr.getJSONObject(i);
                        String tipoftheday = jobj2.optString("tipsoftheday");
                        tii.add(tipoftheday);

                    }

                    List<String> listTemp = tii;
                    Set<String> temp = new HashSet<String>(listTemp);
                    SharedPreferences.Editor editor = getSharedPreferences("MyPref", MODE_PRIVATE).edit();
                    temp.addAll(listTemp);
                    editor.putStringSet("tipoftheday",temp);
                    editor.commit();
 }

我该怎么办?任何人都可以帮助我。

2 个答案:

答案 0 :(得分:1)

  

我已经尝试但是我得到了两次添加的数据,即从中重新获得的数据   共享偏好,然后是来自服务器的数据。

因为在添加新数据之前需要清除tips ArrayList:

      tips.clear();  // clear tips ArrayList
      for(String p : set)
        {
            pojo = new Pojo();
            pojo.setTip(p);
            tips.add(pojo);
        }

答案 1 :(得分:0)

这是一件基本的事情。您正在使用ArrayList在listview中显示数据。现在,如果您从服务器获取新数据,则需要清除您的arraylist对象,如:

tips.clear();

在适配器类中创建setter方法,如:

public void setTipsList(ArrayList tips){
        this.tips=tips;
}

从Activity类中,只需从服务器获取数据即可创建arraylist。

for(String p : set)
        {
            pojo = new Pojo();
            pojo.setTip(p);
            tips.add(pojo);
        }

adapter.setTips(tips);
adapter.notifyDataSetChanged();

调用notifyDataSetChanged()后,listview将显示更改。