adapter.notifyDataSetChanged()无法正常工作,错误在哪里?

时间:2016-10-22 16:00:22

标签: android listview android-recyclerview android-adapter

我无法从链接中成功添加提取的数据。 我不知道错误在哪里,也许是变量列表,但我真的不知道应用程序为什么不想启动。 每次涉及到" adapter.notifyDataSetChanged();"时,应用程序都会崩溃。

我知道这个页面:Adapter.NotifyDataSetChanged doesn't work,但不适合我。

MainActivity.java:

public class RecyclerViewActivity extends AppCompatActivity {
Adapter adapter;
private LinearLayoutManager llm;
private static List<Mymodel> ddd;
final String URL = "url";//this url contains an array: {"user":[{"message":"hi","from":"earth"}]}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main_activity);

    recycler = (RecyclerView)findViewById(R.id.recyclerview);

    linearlm = new LinearLayoutManager(this);
    recycler.setLayoutManager(llm);
    recycler.setHasFixedSize(true);

    //this list is empty, i want only start the adapter
    List<Mymodel> list= new ArrayList<>();
    adapter = new Adapter(list);
    recycler.setAdapter(adapter);

    new myfunction().execute(URL);
    }
public class myfunctionextends AsyncTask<String, String, List<Mymodel>> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected List<Mymodel> doInBackground(String... params) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            String finalJson = buffer.toString();

            JSONObject parentObject = new JSONObject(finalJson);
            JSONArray parentArray = parentObject.getJSONArray("user");


            List<Mymodel> modelist = new ArrayList<>();

            Gson gson = new Gson();
            for (int i = 0; i < parentArray.length(); i++) {
                JSONObject finalObject = parentArray.getJSONObject(i);
                Mymodel mymodel= gson.fromJson(finalObject.toString(), Mymodel.class);
                modelist .add(mymodel);
            }

            return modelist ;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(final List<Mymodel> result) {
        super.onPostExecute(result);
        if (result != null) {
            list.add(new Adapter(result));
            adapter.notifyDataSetChanged();
        }else{
            Toast.makeText(getApplicationContext(), "manca internet", Toast.LENGTH_SHORT).show();
        }
    }

}

Adapter.java:

public class Adapter extends RecyclerView.Adapter<RVAdapter.ViewHolder> {
public static class ViewHold erextends RecyclerView.ViewHolder {

    TextView message;
    TextView from;

    ViewHolder(View itemView) {
        super(itemView);
        message = (TextView)itemView.findViewById(R.id.message);
        from = (TextView)itemView.findViewById(R.id.from);
    }
}

List<Mymodel> user;

Adapter(List<Mymodel> user){
    this.user= user;
}

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
    ViewHolder pvh = new ViewHolder(v);
    return pvh;
}

@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
    viewHolder.message.setText(user.get(i).getMessage());
    iewHolder.from.setText(user.get(i).getFrom());
}

@Override
public int getItemCount() {
    return user.size();
}
}

Mymodel.java:

public String from;
public String message;

public String getMessage() { return message; }

public String getFrom() { return from; }

2 个答案:

答案 0 :(得分:2)

试试这个,

@Override
protected void onPostExecute(final List<Mymodel> result) {        
    if (result != null) {
        // remove existing elements to prevent duplicates
        list.clear();
        // update dataset
        list.addAll(result);
        // notify the adapter
        adapter.notifyDataSetChanged();
    } else {
        Toast.makeText(getApplicationContext(), "manca internet", Toast.LENGTH_SHORT).show();
    }
}

答案 1 :(得分:0)

而不是list.add(new Adapter(result));将新项目添加到adapter内的列表,即user。它会工作的。