单击RecycleView项时更新列表视图

时间:2016-06-20 07:23:46

标签: java android listview android-recyclerview recycler-adapter

我创建了一个listView,它在同一页面的Reycleview中单击项目时更新。 日期提取工作正常,json数据在adpater中获取和更新,但新项目使用listview中的先前数据进行扩展

布局

enter image description here

第一行是RecycleView,下面是Listview,当在clickview中点击上面的项目时,Listview应该更新

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sharanjit.fitness.R;
import com.google.gson.JsonArray;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;


public class AllExercise extends AppCompatActivity {

    ListView list;
    ProgressDialog dialog;
    Context context;
    GetJSONData getJSONData;
    String[] name = {"Abdominals","Arms","Back","Chest","Shoulders","Legs","Cardio"};
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    AllExerciseAdapter adapter;
    ArrayList<Exercise> arrayList;
    boolean first=true;
    int pos=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.allexercises);
        dialog=new ProgressDialog(this);
        context=getApplicationContext();
        getJSONData=new GetJSONData();
        arrayList=new ArrayList<>();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycle);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager =  new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new MyAdapter();
        mRecyclerView.setAdapter(mAdapter);
        new FetchData().execute();

        list = (ListView) findViewById(R.id.exercise_list);

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent(AllExercise.this,ExerciseView.class);
                startActivity(intent);
            }
        });

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id=item.getItemId();

        if(id==16908332)
        {
            finish();
        }

        return super.onOptionsItemSelected(item);
    }

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

        public class ViewHolder extends RecyclerView.ViewHolder {

            public ImageView imageView;
            public ViewHolder(View v) {
                super(v);
                imageView = (ImageView)v.findViewById(R.id.imageView11);

            }
        }

        public MyAdapter() {

        }

        @Override
        public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.exercise_item, parent, false);
          final  ViewHolder vh = new ViewHolder(v);
            vh.imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pos=vh.getAdapterPosition();
                    first=false;
                    new FetchData().execute();
                }
            });
            return vh;
        }


        @Override
        public void onBindViewHolder(ViewHolder holder, final int position) {
            final ViewHolder viewHolder=holder;
            viewHolder.imageView.setImageResource(Constants.exercise_images[position]);
        }

        @Override
        public int getItemCount() {

            return 7;
        }
    }
    public class AllExerciseAdapter extends ArrayAdapter  {


        final private Context cx;

        final private int pos;

        AllExerciseAdapter(Context cx,int pos) {

            super(cx, R.layout.allexercise_list_item, arrayList);

            this.cx = cx;

            this.pos=pos;
        }

        @Override
        public View getView(int position, View vw, ViewGroup group) {
            vw = View.inflate(cx, R.layout.allexercise_list_item, null);
            ImageView imageView=(ImageView)vw.findViewById(R.id.imageView11);
            TextView title=(TextView)vw.findViewById(R.id.textView14);
            TextView cat=(TextView)vw.findViewById(R.id.textView13);

            title.setText(arrayList.get(position).names);
            cat.setText(arrayList.get(position).category);
            if(position==0)
                Log.e("MS",title.getText().toString());

            return vw;
        }
    }

    private class FetchData extends AsyncTask<String,String,String>
    {
        String url="";
        String data="";

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog.setMessage("In Progress...");
            dialog.setCancelable(false);
            dialog.show();
            url="http://www.searchdata.in/fitness/get-exercises.php";
            try {

             data = URLEncoder.encode("category", "UTF-8") + "=" + URLEncoder.encode(name[pos], "UTF-8");

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

        }

        @Override
        protected String doInBackground(String... params) {
            String s=  getJSONData.getData(url,data);
            return s;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            Log.e("sss",s);

            try {
                JSONArray array=new JSONArray(s);
                for(int i=0;i<array.length();i++)
                {
                    JSONObject object=array.getJSONObject(i);
                    Exercise exercise=new Exercise();
                    exercise.names=object.getString("name");
                    exercise.category=object.getString("category");
                    exercise.decription=object.getString("description");
                    arrayList.add(exercise);
                }
                    dialog.dismiss();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.e("ss",""+first);
            adapter = new AllExerciseAdapter(context,pos);
            if(!first) {
                list.setAdapter(adapter);
                adapter.notifyDataSetChanged();

                      }
else {
                list.setAdapter(adapter);




            }
        }
    }

    private class Exercise
    {
        public String names;
        public String decription;
        public String category;
        public String imagePath;
    }

}

3 个答案:

答案 0 :(得分:0)

您需要对代码进行一些小改动 -

if(!first) {
          list.setAdapter(adapter);
          adapter.notifyDataSetChanged(); // No needed to do for first time
}
else {
          list.setAdapter(adapter); // Need to call only once.
          adapter.notifyDataSetChanged();// Here you need to call it to reflect changes   

 }

您需要在onPostExecute中再做一次更改 -

try {
            JSONArray array=new JSONArray(s);
            arraList.clear();   //Add this line
            for(int i=0;i<array.length();i++)

希望它会有所帮助:)

答案 1 :(得分:0)

只需通过以下代码更改onPostExecute方法。

     @Override
     protected void onPostExecute(String s) {
        super.onPostExecute(s);

        Log.e("sss",s);

        try {
            arrayList=new ArrayList<>();
            JSONArray array=new JSONArray(s);
            for(int i=0;i<array.length();i++)
            {
                JSONObject object=array.getJSONObject(i);
                Exercise exercise=new Exercise();
                exercise.names=object.getString("name");
                exercise.category=object.getString("category");
                exercise.decription=object.getString("description");
                arrayList.add(exercise);
            }
                dialog.dismiss();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e("ss",""+first);
        adapter = new AllExerciseAdapter(context,pos);

         list.setAdapter(adapter);
        /*if(!first) 
         {
            adapter.notifyDataSetChanged();

         }
         else {
            list.setAdapter(adapter);
         }*/
    }

答案 2 :(得分:0)

此行适用于代码: -

adapter = new AllExerciseAdapter(context,arrayList);
adapter.setNotifyOnChange(true); // <-----
list.setAdapter(adapter);