如何在listview上更改cardviews上的数据集

时间:2018-04-26 09:31:22

标签: android listview android-cardview

我创建了一个具有不同主题的自定义列表视图。我想在点击特定列表视图项目时生成的卡片视图上设置不同的数据。

这是sqlitehelper:

public class MySqliteHelper extends SQLiteOpenHelper {
private Context context;
public SQLiteDatabase db;
public static final String DATABASE = "Exam_details";

public final String CREATE_TABLE_USER_DATA = "create table User_Data(" +
        "UserID text primary key," +
        "Password text not null," +
        "Contact varchar," +
        "EmailID varchar(45) not null" +
        ")";

public final String CREATE_TABLE_USER_STATS = "create table User_Stats(" +
        "UserID text primary key," +
        "Attempted integer," +
        "Correct integer," +
        "Incorrect integer," +
        "Analysis text not null," +
        "Time_taken time" +
        ")";

public final String CREATE_TABLE_QUESTION = "create table User_Question(" +
        "_id integer primary key autoincrement," +
        "question text," +
        "CorrectAns text," +
        "Opt1 text not null," +
        "Opt2 text not null," +
        "Opt3 text not null," +
        "Opt4 text not null" +
        ")";

public void close() {
    db.close();
}

public String getSingleEntry(String UserId) {
    db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("Select UserID,Password from User_Data where UserID='" + UserId + "'", null);
    String a, b;
    b = "Not Found in Database";
    if (cursor.moveToFirst()) {
        do {
            a = cursor.getString(0);
            b = cursor.getString(1);

            if (a.equals(UserId)) {
                b = cursor.getString(1);
                break;
            }
        } while (cursor.moveToNext());
    }
    return b;
}

public void UpdateEntry(String userId, String password) {
    ContentValues updatevalues = new ContentValues();
    updatevalues.put("password", password);
    updatevalues.put("userid", userId);
    db.update("User_Data", updatevalues, "UserID=?", new String[]{userId});
}

public void addQuestion(Question question) {
    db = this.getWritableDatabase();
    ContentValues vals = new ContentValues();
    vals.put("question", question.getQuestion());
    vals.put("CorrectAns", question.getCorrect_ans());
    vals.put("Opt1", question.getOpt1());
    vals.put("Opt2", question.getOpt2());
    vals.put("Opt3", question.getOpt3());
    vals.put("Opt4", question.getOpt4());
    db.insert("User_Question", null, vals);
}

public List<Question> getQuestions() {
    ArrayList<Question> quesList = new ArrayList<>();
    db = this.getReadableDatabase();
    String selQuery = "Select * from User_Question";
    Cursor cursor = db.rawQuery(selQuery, null);
    if (cursor.moveToFirst()) {
        do {
            Question question = new Question();
            question.setQuestionid(cursor.getInt(0));
            question.setQuestion(cursor.getString(1));
            question.setCorrect_ans(cursor.getString(2));
            question.setOpt1(cursor.getString(3));
            question.setOpt2(cursor.getString(4));
            question.setOpt3(cursor.getString(5));
            question.setOpt4(cursor.getString(6));
            quesList.add(question);
        } while (cursor.moveToNext());
    }
    return quesList;
}

public int rowCount() {
    int row;
    String selQuery = "Select * from User_Question";
    db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selQuery, null);
    row = cursor.getCount();
    return row;
}

public MySqliteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);
    this.context=context;
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE_USER_DATA);
    db.execSQL(CREATE_TABLE_USER_STATS);
    db.execSQL(CREATE_TABLE_QUESTION);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table if exists User_Data");
    db.execSQL("drop table if exists User_Stats");
    db.execSQL("drop table if exists Question");
    onCreate(db);
}

public void addQuestions() {
    int rc=this.rowCount();

    if(rc==0) {
        Question q1 = new Question("Name the Android 6 version", "Marshmallow", "Marshmallow", "JellyBean", "Oreo", "Lollipop");
        this.addQuestion(q1);

        Question q2 = new Question("What does ADT stands for", "Android Development Tool",  "Android Development Tool","Android Development Toolkit", "Android Design Tool", "Android Designing Tool");
        this.addQuestion(q2);

        Question q3 = new Question("Name the Android runtime", "Dalvik", "JVM", "JRE", "Gradle", "Dalvik");
        this.addQuestion(q3);

        Question q4 = new Question("Which of the following are resources", "All of the above", "JSON", "Bitmap", "XML", "All of the above");
        this.addQuestion(q4);

    }
    else
    {
        Log.e("Tag","questions Added!!");
    }
}

}

Cardview适配器的代码:

class CardviewAdapter extends RecyclerView.Adapter<CardviewAdapter.CardviewViewHolder> {
private final LayoutInflater inflater;
List<Question> data;
int Questionid = 0;
Question currentCard;
Context context;
public static int score = 0;
String[] correctans={"Marshmallow","Android Development Tool","Dalvik","All of the above"};

public CardviewAdapter(Context context, List<Question> data) {
    inflater = LayoutInflater.from(context);
    this.data = data;
    this.context = context;
}

@Override
public CardviewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.card, parent, false);
    CardviewViewHolder Viewholder = new CardviewViewHolder(view);
    return Viewholder;
}

@Override
public void onBindViewHolder(final CardviewViewHolder holder, int position) {
   // holder.setIsRecyclable(false);
   final int pos=holder.getAdapterPosition();
    Log.d("Tag", "position >> "+ pos);
    currentCard = data.get(pos);


    //correctans=data.get(pos).getCorrect_ans();
   // currentCard=data.get(Questionid);
    holder.question.setText(currentCard.getQuestion());
    holder.opt1.setText(currentCard.getOpt1());
    holder.opt2.setText(currentCard.getOpt2());
    holder.opt3.setText(currentCard.getOpt3());
    holder.opt4.setText(currentCard.getOpt4());

   holder.opt1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            holder.opt1.setBackgroundColor(Color.GREEN);
            Log.e("optionValue", holder.opt1.getText()+" "+correctans);
            for(int i=0;i<correctans.length;i++)
            {
                if(holder.opt1.getText().equals(correctans[i]))
                {
                    score++;
                  //  Toast.makeText(context, "score" + score, Toast.LENGTH_SHORT).show();
                }
            }
            }

           /* Log.e("optionValue", holder.opt1.getText()+" "+correctans);
            if (( holder.opt1.getText()==correctans[0] || correctans[1] || correctans[2] || correctans[3]) ) {
                score++;
                Toast.makeText(context, "score" + score, Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(context, "wrong score" + score, Toast.LENGTH_SHORT).show();
            }

        }*/
    });

    holder.opt2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            holder.opt2.setBackgroundColor(Color.GREEN);
            Log.e("optionValue", holder.opt2.getText()+" "+correctans);
            for(int i=0;i<correctans.length;i++)
            {
                if(holder.opt2.getText().equals(correctans[i]))
                {
                    score++;
                  //  Toast.makeText(context, "score" + score, Toast.LENGTH_SHORT).show();
                }
            }
        }
    });

    holder.opt3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            holder.opt3.setBackgroundColor(Color.GREEN);
            Log.e("optionValue", holder.opt3.getText()+" "+correctans);
            for(int i=0;i<correctans.length;i++)
            {
                if(holder.opt3.getText().equals(correctans[i]))
                {
                    score++;
                   // Toast.makeText(context, "score" + score, Toast.LENGTH_SHORT).show();
                }
            }
        }
    });

    holder.opt4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            holder.opt4.setBackgroundColor(Color.GREEN);
            Log.e("optionValue", holder.opt4.getText()+" "+correctans);
            for(int i=0;i<correctans.length;i++)
            {
                if(holder.opt4.getText().equals(correctans[i]))
                {
                    score++;
                   // Toast.makeText(context, "score" + score, Toast.LENGTH_SHORT).show();
                }
            }
        }
    });

    if(pos>2){
        holder.submit.setVisibility(View.VISIBLE);
    }
    holder.submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i=new Intent(context,Result.class);
            i.putExtra("score",score);
            context.startActivity(i);
        }
    });

}

@Override
public int getItemCount() {
 //   Toast.makeText(context,"size: "+data.size(),Toast.LENGTH_SHORT).show();
    return data.size();
}

class CardviewViewHolder extends RecyclerView.ViewHolder {
    TextView question;
    TextView opt1, opt2, opt3, opt4;
    CircleImageView civ;
    Button submit;


    public CardviewViewHolder(View itemView) {
        super(itemView);

        question = (TextView) itemView.findViewById(R.id.question);
        opt1 = (TextView) itemView.findViewById(R.id.opt1);
        opt2 = (TextView) itemView.findViewById(R.id.opt2);
        opt3 = (TextView) itemView.findViewById(R.id.opt3);
        opt4 = (TextView) itemView.findViewById(R.id.opt4);
        civ = (CircleImageView) itemView.findViewById(R.id.civ);
        submit=(Button) itemView.findViewById(R.id.submit);
    }
}

}

listview的代码(我把它当作片段):

public class Topic extends Fragment {
ListView lv;
MyArrayAdapter adap;
String[] topics;
Vector<mypojo> v = new Vector<>();
mypojo pojo;
public static int[] list_img;


public Topic() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_topic, container, false);
    list_img = new int[11];
    list_img[0] = R.drawable.basics;
    list_img[1] = R.drawable.view;
    list_img[2] = R.drawable.events;
    list_img[3] = R.drawable.menu;
    list_img[4] = R.drawable.service;
    list_img[5] = R.drawable.broadcast;
    list_img[6] = R.drawable.webservice1;
    list_img[7] = R.drawable.webservice;
    list_img[8] = R.drawable.sensor;
    list_img[9] = R.drawable.widgets;
    list_img[10] = R.drawable.animation;
    lv = (ListView) view.findViewById(R.id.lv);
    topics = getResources().getStringArray(R.array.topics);

    for (int i = 0; i < topics.length; i++) {
        pojo = new mypojo(list_img[i], topics[i]);
        v.add(pojo);
    }
    adap = new MyArrayAdapter(getActivity(), v);
    lv.setAdapter(adap);

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            int pos=parent.getSelectedItemPosition();
            SharedPreferences preferences= PreferenceManager.getDefaultSharedPreferences(getActivity());
           // SharedPreferences prefs=getActivity().getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor=preferences.edit();
            editor.putInt("Position",pos).commit();

            Intent i = new Intent(getActivity(), Cardview.class);
            startActivity(i);

        }
    });
    return view;
}

}

请查看代码并告诉如何更改listview点击数据(例如,我想在点击Basics时更改cardviews的内容,然后点击Views等更改它...)< / p>

1 个答案:

答案 0 :(得分:0)

您可以使用def execute(env: Environment): Value = { val envThis = env(name) println(this.getClass) envThis match { case text: Text => text.body.execute(env) case thunk: Thunk => thunk() case other => other } }

通知RecyclerView Adapter中整个数据集的更改

或使用adapter.notifyDataSetChanged()

通知仅更改记录

只需执行(1)更新RecyclerView(2)调用adapter.notifyXXX的数据 在onClickListener.onClick回调