Question Question - 1 month ago 10
Android Question

adapter.notifyDataSetChanged() doesn't work correctly, where is the error?

I can not add successfully extracted data from the link.
I don't know where is the error, maybe is the variable 'list', but really i don't know why the application don't want start.
The application crashes every time when it comes to "adapter.notifyDataSetChanged();".

I know of this page: Adapter.NotifyDataSetChanged doesn't work , but don't work for me.

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; }

Answer

Try this,

@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();
    }
}