放置adapter.notifyDataSetChanged()的位置;当使用Volley时

时间:2016-05-03 04:26:39

标签: android json arraylist adapter android-volley

此代码运行正常,将我的JSON响应显示在Arraylist中。问题是,每次单击按钮再次显示列表时,它只会复制先前的JSON响应,从而产生重复结果列表。

每次点击按钮,删除以前的所有结果,如何让它刷新arraylist?我需要放置另一个notifyDataSetChanged吗?如果是的话,在哪里?

Details.java代码:

public class Details extends AppCompatActivity {

    private static final String TAG = Details.class.getSimpleName();
    String url="removed";
    private Button ShowDetailsButton;
    private Button AddDetails;
    private CustomListAdapter adapter;
    private ProgressDialog pDialog;
    private List<LoadUsers> mList = new ArrayList<LoadUsers>();
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.studio_student_view);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        listView = (ListView) findViewById(R.id.lv);
        adapter = new CustomListAdapter(this, mList);
        listView.setAdapter(adapter);

        ShowDetailsButton = (Button) findViewById(R.id.show_details);
        AddDetails = (Button) findViewById(R.id.add_details);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

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

                // Creating volley request obj
                JsonArrayRequest studentReq = new JsonArrayRequest(url,
                        new Response.Listener<JSONArray>() {
                            @Override
                            public void onResponse(JSONArray response) {
                                Log.d(TAG, response.toString());
                                hidePDialog();

                                // Parsing json
                                for (int i = 0; i < response.length(); i++) {
                                    try {

                                        JSONObject obj = response.getJSONObject(i);
                                        LoadUsers details = new LoadUsers();
                                        details.setTitle(obj.getString("name"));
                                        details.setThumbnailUrl(obj.getString("image"));
                                        details.setEmail(obj.getString("email"));
                                        details.setPhone(obj.getString("phone"));

                                        // adding 
                                        mList.add(details);

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

                                }

                                // notifying list adapter about data changes
                                // so that it renders the list view with updated data
                                adapter.notifyDataSetChanged();
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        hidePDialog();

                    }

                });

                // Adding request to request queue
                AppController.getInstance().addToRequestQueue(studentReq);
            }

        });

    }
    public void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }
}

CustomListAdapter.java代码:

public class CustomListAdapter extends BaseAdapter {
    private Activity activity;
    private LayoutInflater inflater;
    private List<LoadUsers> usersItems;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    public CustomListAdapter(Activity activity, List<LoadUsers> usersItems) {
        this.activity = activity;
        this.usersItems = usersItems;
    }

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

    @Override
    public Object getItem(int location) {
        return usersItems.get(location);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (inflater == null)
            inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.list_row, null);

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();
            NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail);
            TextView title = (TextView) convertView.findViewById(R.id.title);
            TextView email = (TextView) convertView.findViewById(R.id.lvemail);
            TextView phone = (TextView) convertView.findViewById(R.id.lvphone);


            // getting user data for the row
            LoadUsers m = usersItems.get(position);

            // thumbnail image
            thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);

            // title
            title.setText(m.getTitle());

            // email
            email.setText("Email: " + String.valueOf(m.getEmail()));

            // phone
            phone.setText("Phone: " + String.valueOf(m.getPhone()));

            return convertView;

    }

}

4 个答案:

答案 0 :(得分:1)

<强>错误:

数据正在重复,因为您没有清除具有先前数据集的ArrayList。

<强>解决方案: 在进行API调用之前清除ArrayList。在您的情况下,这应该是按钮单击侦听器代码中的第一行!

// clear collection 
mList.clear();

答案 1 :(得分:1)

您可以在# # This is a Shiny web application. You can run the application by clicking # the 'Run App' button above. # # Find out more about building applications with Shiny here: # # http://shiny.rstudio.com/ # library(dplyr) library(EcoHydRology) library(ggplot2) library(shiny) if ( require(EcoHydRology) ) { detach("package:dplyr", unload = TRUE) detach("package:EcoHydRology", unload = TRUE) require(dplyr) } ui <- fluidPage( titlePanel( sidebarLayout( sidebarPanel( tags$h1(tags$strong("Shiny app")), fileInput("file", "Upload your file"), width =2), mainPanel(width =10, uiOutput("tb"))))) #server server <- function(input,output){ data <- reactive({ file1 <- input$file if(is.null(file1)){return()} read.csv(file1$datapath, header=TRUE, sep=',') }) output$sum <- renderTable({ if(is.null(data())){return ()} df_summary <- data() df_summary1 <- df_summary %>% dplyr::select(cut, color, carat, price) summary(df_summary1) }) output$table <- renderDataTable({ if(is.null(data())){return ()} data() }) output$stats <- renderDataTable({ if(is.null(data())){return ()} diam1 <- data() print( diam_stats <- diam1 %>% dplyr::select(cut, color, carat) %>% dplyr::arrange(cut, color) %>% dplyr::group_by(cut, color) %>% dplyr::filter(!is.na(carat)) %>% dplyr::summarise_each(funs( mean(., na.rm=T), sd(., na.rm=T), n())) ) }) output$tb <- renderUI({ if(is.null(data())) h5() else tabsetPanel(type="tab", tabPanel(h3("Summary", align="center"), tableOutput("sum")), tabPanel(h3("Data"), dataTableOutput("table")), tabPanel(h3("Stats"), dataTableOutput("stats"))) }) } shinyApp(ui = ui, server = server) 之后添加mList.clear() 您也可以使用public void onResponse(JSONArray response)方法添加适配器中的所有元素并通知一次,否则如果您使用mList.addAll(),则每次添加单个项目时都会通知。

请注意,通知是在内部完成的。

答案 2 :(得分:1)

谢谢。它奏效了!

解决方案:

&#13;
&#13;
public class Details extends AppCompatActivity {

    private static final String TAG = Details.class.getSimpleName();
    String url="removed";
    private Button ShowDetailsButton;
    private Button AddDetails;
    private CustomListAdapter adapter;
    private ProgressDialog pDialog;
    private List<LoadUsers> mList = new ArrayList<LoadUsers>();
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.studio_student_view);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        listView = (ListView) findViewById(R.id.lv);
        adapter = new CustomListAdapter(this, mList);
        listView.setAdapter(adapter);

        ShowDetailsButton = (Button) findViewById(R.id.show_details);
        AddDetails = (Button) findViewById(R.id.add_details);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        ShowDetailsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
          
          mList.clear();

                // Creating volley request obj
                JsonArrayRequest studentReq = new JsonArrayRequest(url,
                        new Response.Listener<JSONArray>() {
                            @Override
                            public void onResponse(JSONArray response) {
                                Log.d(TAG, response.toString());
                                hidePDialog();

                                // Parsing json
                                for (int i = 0; i < response.length(); i++) {
                                    try {

                                        JSONObject obj = response.getJSONObject(i);
                                        LoadUsers details = new LoadUsers();
                                        details.setTitle(obj.getString("name"));
                                        details.setThumbnailUrl(obj.getString("image"));
                                        details.setEmail(obj.getString("email"));
                                        details.setPhone(obj.getString("phone"));

                                        // adding 
                                        mList.add(details);

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

                                }

                                // notifying list adapter about data changes
                                // so that it renders the list view with updated data
                                adapter.notifyDataSetChanged();
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        hidePDialog();

                    }

                });

                // Adding request to request queue
                AppController.getInstance().addToRequestQueue(studentReq);
            }

        });

    }
    public void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }
}
&#13;
&#13;
&#13;

答案 3 :(得分:1)

我们有两种方法,

  1. 您想要清除所有数据并完全更新列表。
  2. 您想要添加一些新数据以列出并显示旧数据+新数据
  3. 方法1:

     @Override
     public void onResponse(JSONArray response) {
        Log.d(TAG, response.toString());
        hidePDialog();
        // CLEAR YOUR OLD DATA HERE
        mList.clear();
        // Parsing json
        for (int i = 0; i < response.length(); i++) {
        try {
            JSONObject obj = response.getJSONObject(i);
            LoadUsers details = new LoadUsers();
            details.setTitle(obj.getString("name"));
            details.setThumbnailUrl(obj.getString("image"));
            details.setEmail(obj.getString("email"));
            details.setPhone(obj.getString("phone"));
            // adding 
            mList.add(details);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    
      }
      // notifying list adapter about data changes
      // so that it renders the list view with updated data
      adapter.notifyDataSetChanged();
    

    按照此方法,您的列表将再次续订。

    方法2:

    您只想添加新数据,并希望为新添加的项目显示动画。

     @Override
     public void onResponse(JSONArray response) {
        Log.d(TAG, response.toString());
        hidePDialog();
        // MAKE A NEW LIST HERE AND ADD NEW DATA TO IT
        private List<LoadUsers> mListNewItems = new ArrayList<LoadUsers>();
        // Parsing json
        for (int i = 0; i < response.length(); i++) {
        try {
            JSONObject obj = response.getJSONObject(i);
            LoadUsers details = new LoadUsers();
            details.setTitle(obj.getString("name"));
            details.setThumbnailUrl(obj.getString("image"));
            details.setEmail(obj.getString("email"));
            details.setPhone(obj.getString("phone"));
            // ADD NEW DATA TO NEW LIST 
            mListNewItems.add(details);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // IMPORTANT TASK SHOULD DONE HERE
        // Get Old Size Of the List before adding new data to notify new inserted items
        int oldSize=mList.getSize();
        // here we check whether we have such a data in our list. if we had, we dnt add that, otherwise add new data to our list
        for (int i=0;i<mListNewItems.size();i++){
        if(!mList.contain(mListNewItems.get(i))){
            mList.add(mListNewItems.get(i));
        }
        }
    
        //check how many new items added
        int numberOfNewItems=mList.getSize()-oldSize;
    
        // Here you should use notifyItemRangeInserted instead of notifyDataSetChange as it is less time consuming than notifyDataSetChange and also it let you to show animation for new added items.
        adapter.notifyItemRangeInserted(oldSize,numberOfNewItems);
      }