I am trying to test my code by using Mockito
static class SongAdapterPresenter implements SortedSongSelectionContract.SongAdapterContract.Presenter {
private List<Song> songs;
private final Presenter sortedSongSelectionPresenter;
private final SortedSongSelectionContract.SongAdapterContract.Adapter adapter;
private SortedSongSelectionContract.SongAdapterContract.SongView selectedSongView;
private Song selectedSong;
SongAdapterPresenter(SortedSongSelectionContract.SongAdapterContract.Adapter adapter, SortedSongSelectionContract.Presenter sortedSongSelectionPresenter) {
this.adapter = adapter;
this.sortedSongSelectionPresenter = sortedSongSelectionPresenter;
}
#Override
public int getItemCount() {
return songs != null ? songs.size() : 0;
}
#Override
public void onBindView(SortedSongSelectionContract.SongAdapterContract.SongView songView, int position) {
Song song = songs.get(position);
songView.setTitle(song.getName());
songView.setArtists(song.getArtists());
List<Genre> genres = song.getGenres();
int size = genres.size();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < size; i++) {
builder.append(genres.get(i).getName()).append(",");
}
int length = builder.length();
if (length > 0) {
builder.deleteCharAt(length - 1);
}
songView.setGenres(builder.toString());
songView.showPlayIcon(true);
boolean select = isSongEqual(song);
if (select) {
selectedSongView = songView;
}
songView.showSelectionUi(select);
}
#Override
public void onItemClicked(SortedSongSelectionContract.SongAdapterContract.SongView songView, int position) {
Song song = songs.get(position);
if (isSongEqual(song)) {
return;
}
deSelect(song);
selectedSongView = songView;
selectedSongView.showSelectionUi(true);
selectedSong = songs.get(position);
sortedSongSelectionPresenter.getBus().post(new BusEvents.SongSelected(selectedSong));
}
#Override
public void setSongs(List<Song> songs) {
this.songs = songs;
adapter.refresh();
}
#Override
public void deSelect(Song song) {
if (!isSongEqual(song)) {
if (selectedSongView != null) {
selectedSongView.showSelectionUi(false);
}
selectedSong = null;
selectedSongView = null;
}
}
private boolean isSongEqual(Song song) {
return !(song == null || selectedSong == null) && (song == selectedSong || selectedSong.getId().equals(song.getId()));
}
}
//endregion
//region Instance methods
private void processEvent(Object event) {
if (event instanceof BusEvents.SongSelected) {
deSelect(((BusEvents.SongSelected) event).getSong());
}
}
//endregion
}
I want to write test for onBindView
Following is my Test Class
RunWith(PowerMockRunner.class)
#PrepareForTest(Log.class)
public class SongAdapterPresenterTest {
private SortedSongSelectionPresenter.SongAdapterPresenter songAdapterPresenter;
#Mock
private SortedSongSelectionContract.SongAdapterContract.Adapter adapter;
#Mock
private SortedSongSelectionContract.Presenter presenter;
#Mock
private SortedSongSelectionContract.SongAdapterContract.SongView songView;
private Song song;
private List<Song> songList;
#Before
public void setUp() {
song = new Song("1", "A", "B");
songList = new ArrayList<>(1);
songList.add(song);
songAdapterPresenter = new SortedSongSelectionPresenter.SongAdapterPresenter(adapter, presenter);
}
#Test
public void getItemCountWithSongListNotNull_returnSongListSize() {
songAdapterPresenter.setSongs(songList);
Assert.assertEquals(songList.size(), songAdapterPresenter.getItemCount());
}
#Test
public void getItemCountWithSongListNull_returnIsZero(){
songAdapterPresenter.setSongs(null);
Assert.assertEquals(0, songAdapterPresenter.getItemCount());
}
#Test
public void testonBindView() {
songAdapterPresenter.onBindView(songView, 1);
verify(songView).showSelectionUi(true);
}
#Test
public void deSelect_SongRemoved(){
songAdapterPresenter.deSelect(song);
verify(songView).showSelectionUi(false);
}
}
I have created Mock Object of View and object of my PresenterAdapter class. I am not getting what causes the error.
I keep getting NullPointer when i execute my onBindView Test
Any help would be greatly appreciated.
You never call setSongs and that's why you get a NullPointerException.
Also note that your songList has only one element.
Change your code to:
#Test
public void testonBindView() {
songAdapterPresenter.setSongs(songList);
songAdapterPresenter.onBindView(songView, 0);
verify(songView).showSelectionUi(true);
}
Related
Can someone explain my error by showing me why each update of the Room database causes an event on the liveData despite the removeObservers that I apply before?
When I reactivate observe, I have as many events as there were updates. If I do 6 updateLobjet, I can have updateLobjetsList 8 times.
What should I do to be notified only once, or none if one is not possible, but continuing to observe for next event?
I need to use a LiveData to retrieve my data from the Room database and have it displayed by the RecyclerView.
I really need help to solve that.
Fragment:
public class MainFragment extends Fragment {
private ArrayList<Lobjet> mLobjets = new ArrayList<>();
RecyclerView mRecyclerView;
private LobjetViewModel mLobjetViewModel;
SampleAdapter mSampleAdapter;
LiveData<List<Lobjet>> mLDgetAll;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
this.mSampleAdapter = new SampleAdapter();
this.mRecyclerView = view.findViewById(R.id.sampleRecyclerView);
this.mRecyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
this.mRecyclerView.setAdapter(this.mSampleAdapter);
Button add = view.findViewById(R.id.add);
add.setOnClickListener(v -> {
Random r = new Random();
this.mLobjetViewModel.insertLobjet(new Lobjet("Lobjet" + (r.nextInt(9999)), this.mLobjets.size()));
});
this.mLobjetViewModel = new ViewModelProvider(this, ViewModelFactory.getInstance(getContext())).get(LobjetViewModel.class);
this.mLDgetAll = this.mLobjetViewModel.getAll();
this.mLDgetAll.observe(getViewLifecycleOwner(), this::updateLobjetsList);
this.setUpItemTouchHelper();
return view;
}
public void updateLobjetsList(List<Lobjet> lobjets) {
this.mSampleAdapter.setAdapterDatas(this.mLobjets = new ArrayList<>(lobjets));
}
private void updateLobjet(Lobjet lobjet) {
this.mLobjetViewModel.updateLobjet(lobjet);
}
private void setUpItemTouchHelper() {
ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(
ItemTouchHelper.UP | ItemTouchHelper.DOWN, 0) {
#Override
public int getSwipeDirs(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder) {
// pas de swipe en mode sélection d'articles
return super.getSwipeDirs(recyclerView, viewHolder);
}
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
final int from = viewHolder.getBindingAdapterPosition();
final int to = target.getBindingAdapterPosition();
Collections.swap(mLobjets, from, to);
mSampleAdapter.notifyItemMoved(from, to);
return true;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
}
// mettre à jour les données à la fin du drop
#Override
public void clearView(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder) {
super.clearView(recyclerView, viewHolder);
if (mLDgetAll != null && mLDgetAll.hasObservers())
mLDgetAll.removeObservers(getViewLifecycleOwner());
for (int i = 0; i < mLobjets.size(); i++) {
mLobjets.get(i).setOrder(i);
updateLobjet(mLobjets.get(i));
}
if (mLDgetAll != null) {
mLDgetAll.observe(getViewLifecycleOwner(),
lobjets -> {
updateLobjetsList(lobjets);
});
}
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
itemTouchHelper.attachToRecyclerView(this.mRecyclerView);
}
}
Model:
#Entity(indices = {
#Index(value = {"id"}, unique = true),
#Index(value = {"lobjetName"}, unique = true)
})
public class Lobjet {
#PrimaryKey(autoGenerate = true)
private long id;
#ColumnInfo(name = "lobjetName")
private String name;
private long order;
public Lobjet(String name, long order) {
this.name = name;
this.order = order;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setId(long id) {
this.id = id;
}
public long getOrder() {
return order;
}
public void setOrder(long order) {
this.order = order;
}
}
Dao:
#Dao
public interface LobjetDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
long createLobjet(Lobjet lobjet);
#Query("SELECT * FROM Lobjet ORDER BY `order`, lobjetName")
LiveData<List<Lobjet>> getAll();
#Update
int updateLobjet(Lobjet lobjet);
}
Database:
#Database(
version = 1,
entities = {Lobjet.class},
)
public abstract class getDB extends RoomDatabase {
private static final String DB_NAME = "MyDatabase.db";
private static getDB INSTANCE;
public static synchronized getDB getInstance(Context context) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(), getDB.class, DB_NAME)
.fallbackToDestructiveMigration()
.build();
}
return INSTANCE;
}
public abstract LobjetDao lobjetDao();
}
Factory:
public class ViewModelFactory implements ViewModelProvider.Factory {
private final LobjetDataRepository lobjetDataSource;
private final Executor executor;
private static volatile ViewModelFactory factory;
public static ViewModelFactory getInstance(Context context) {
if (factory == null) {
synchronized (ViewModelFactory.class) {
if (factory == null) {
factory = new ViewModelFactory(context);
}
}
}
return factory;
}
private ViewModelFactory(Context context) {
getDB database = getDB.getInstance(context);
this.lobjetDataSource = new LobjetDataRepository(database.lobjetDao());
this.executor = Executors.newSingleThreadExecutor();
}
#Override
#NotNull
public <T extends ViewModel> T create(Class<T> modelClass) {
if (modelClass.isAssignableFrom(LobjetViewModel.class)) {
return (T) new LobjetViewModel(lobjetDataSource, executor);
}
throw new IllegalArgumentException("Unknown ViewModel class");
}
}
Repository:
public class LobjetDataRepository {
private final LobjetDao mLobjetDao;
public LobjetDataRepository(LobjetDao lobjetDao) {
this.mLobjetDao = lobjetDao;
}
public LiveData<List<Lobjet>> getAll() {
return this.mLobjetDao.getAll();
}
public void createLobjet(Lobjet lobjet) {
lobjet.setId(mLobjetDao.createLobjet(lobjet));
}
public void updateLobjet(Lobjet lobjet) {
mLobjetDao.updateLobjet(lobjet);
}
}
ViewModel:
public class LobjetViewModel extends ViewModel {
private final LobjetDataRepository lobjetDataSource;
private final Executor executor;
public LobjetViewModel(LobjetDataRepository lobjetDataSource, Executor executor) {
this.lobjetDataSource = lobjetDataSource;
this.executor = executor;
}
public LiveData<List<Lobjet>> getAll() {
return lobjetDataSource.getAll();
}
public void insertLobjet(Lobjet lobjet) {
executor.execute(() -> lobjetDataSource.createLobjet(lobjet));
}
public void updateLobjet(Lobjet lobjet) {
executor.execute(() -> lobjetDataSource.updateLobjet(lobjet));
}
}
I want to pass the list of itemselected or ItemsInCart to another activity. My Items Model implements parcelable. The problem is am getting error below in my SecondActivity class.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference at com.example.Project1.SecondActivity.onCreate(SecondActivity.java:59)
Below is the code
Model Item;
public class Item implements Parcelable {
private int iid;
private String itenname;
private String itemprice;
private String itemstock;
private int totalInCart;
private List<Item> items;
public Item(int iid, String itenname, String itemprice, String itemstock, int totalInCart,List<Item> items) {
this.iid = iid;
this.itenname = itenname;
this.itemprice = itemprice;
this.itemstock = itemstock;
this.totalInCart = totalInCart;
this.items = items;
}
protected Item(Parcel in) {
iid = in.readInt();
itenname = in.readString();
itemprice = in.readString();
itemstock = in.readString();
totalInCart = in.readInt();
items = in.createTypedArrayList(Item.CREATOR);
}
public static final Creator<Item> CREATOR = new Creator<Item>() {
#Override
public Item createFromParcel(Parcel in) {
return new Item(in);
}
#Override
public Item[] newArray(int size) {
return new Item[size];
}
};
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
public int getIid() {
return iid;
}
public void setIid(int iid) {
this.iid = iid;
}
public String getItenname() {
return itenname;
}
public void setItenname(String itenname) {
this.itenname = itenname;
}
public String getItemprice() {
return itemprice;
}
public void setItemprice(String itemprice) {
this.itemprice = itemprice;
}
public String getItemstock() {
return itemstock;
}
public void setItemstock(String itemstock) {
this.itemstock = itemstock;
}
public int getTotalInCart() {
return totalInCart;
}
public void setTotalInCart(int totalInCart) {
this.totalInCart = totalInCart;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(iid);
dest.writeString(itenname);
dest.writeString(itemprice);
dest.writeString(itemstock);
dest.writeInt(totalInCart);
dest.writeTypedList(items);
}
}
First Activity;
The list that i want to pass to second activity is 'itemsInCart'
buttonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (itemsInCart==null||itemsInCart.size()<=0){
Toast.makeText(List_Items.this, "Please add some items to the cart.", Toast.LENGTH_SHORT).show();
return;
}
ArrayList<Item> additems = new ArrayList<Item>();
for (int i = 0; i < itemsInCart.size(); i++){
additems.add(itemsInCart.get(i));
}
Intent intent = new Intent(MainActivity.this,DisplaySelectedItems.class);
intent.putParcelableArrayListExtra ("Itemselected", additems);
startActivity(intent);
}
});
Second Activity (in OnCreate method):
Bundle bundle = getIntent().getExtras();
ArrayList<Item> selecteditems = bundle.getParcelableArrayList("Itemselected");
CartItemsInRecyclerView.setLayoutManager(new LinearLayoutManager(this));
placeOrderAdapter = new PlaceOrder_Adapter((ArrayList<Item>) items); <- This is line 59 of the error
CartItemsInRecyclerView.setAdapter(placeOrderAdapter);
I have found similar questions and tried their solutions but all is not working.
Please advise on what i have to change.
Second Activity Adapter.
public class SecondActivity_Adapter extends RecyclerView.Adapter<SecondActivity_Adapter.MyViewHolder> {
private ArrayList itemList;
public SecondActivity_Adapter(ArrayList<Item> itemList){
this.itemList = itemList;
}
public void updateData(ArrayList<Item> itemList){
this.itemList = itemList;
notifyDataSetChanged();
}
#NonNull
#Override
public SecondActivity_Adapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_of_place_order,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SecondActivity_Adapter.MyViewHolder holder, int position) {
holder.name.setText(itemList.get(position).getItenname());
holder.price.setText("Unit Price: "+String.format("%.0f",itemList.get(position).getItemprice())+"/=");
holder.QTY.setText("Qty: "+itemList.get(position).getTotalInCart());
}
#Override
public int getItemCount() {
return 0;
}
static class MyViewHolder extends RecyclerView.ViewHolder {
TextView menuName,menuPrice,menuQTY,tvCount;
public MyViewHolder(View view){
super(view);
name = view.findViewById(R.id.menuName);
price = view.findViewById(R.id.menuPrice);
QTY = view.findViewById(R.id.menuQTY);
tvCount = view.findViewById(R.id.tvCount);
}
}
}
Check whether you have added RecyclerView in xml i.e, activity_second.xml
If you have added Recyclerview in xml check whether you have referenced it using findViewById in SecondActivity
RecyclerView CartItemsInRecyclerView = findViewById(R.id.recyclerview_id)
You are getting error for Layout Manager i.e referencing it using null object reference , that means CartItemsInRecyclerView is null
Edit :
In First activity:-
for (int i = 0; i < itemsInCart.size(); i++){
additems.add(itemsInCart.get(i));
}
//log statement
for (int i = 0; i < additems.size(); i++){
Log.d("firstActivity",i.getItenname())
}
In Second Activity:-
Instead of bundle.getgetParcelableArrayList try getIntent().getgetParcelableArrayList
ArrayList<Item> selecteditems =
getIntent().getParcelableArrayList("Itemselected");
//log statement
if(selecteditems.size()!=0){
for (int i = 0; i < selecteditems.size(); i++){
Log.d("secondActivity",i.getItenname())
}
}else{
Log.d("secondActivity","empty data")
}
Then check the result in Logcat
I am trying to make a mobile version of a board game and for some reason I have an ArrayList where all elements conform to the last element whenever a new one is added and I can´t figure out why.
(i am pretty new to Android Studio)
Below are all the classes that are concerned with adding to the list:
public class ScoreBoard {
private static final ScoreBoard ourInstance = new ScoreBoard();
public static ScoreBoard getInstance() {
return ourInstance;
}
List<Player> Players;
int nrOfPlayers;
int activePlayer;
private ScoreBoard() {
Players = new ArrayList<Player>();
}
public void addPlayer(CharSequence name) {
Player p = new Player(name);
Players.add(p);
}
public void nrOfPlayers(int number)
{
nrOfPlayers = number;
}
public boolean stop()
{
boolean stop = false;
if (nrOfPlayers <= Players.size())
{
stop = true;
}
return stop;
}
public void StartGame()
{
Random random = new Random();
random.nextInt(nrOfPlayers);
}
public CharSequence GetActivePlayerName()
{
return Players.get(activePlayer).name;
}
}
public class Player {
public CharSequence name;
public int points;
public Player(CharSequence name)
{
this.name = name;
}
}
public class PlayerName extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player_name);
}
public void addPlayer(View view)
{
ScoreBoard SB = ScoreBoard.getInstance();
TextView nameText = (TextView)findViewById(R.id.NameText);
TextView playerText = (TextView)findViewById(R.id.PlayerText);
CharSequence name = nameText.getText();
SB.addPlayer(name);
playerText.setText("Player " + (SB.Players.size() + 1) + " enter your name");
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, name + " Added", duration);
toast.show();
if(SB.stop())
{
SB.StartGame();
Intent intent = new Intent(this, TakeTurn.class);
startActivity(intent);
}
else
{
}
}
}
You've used static and final while initializing. Remove them and modify your Scorecard class as follows:
private ScoreBoard ourInstance = new ScoreBoard();
public ScoreBoard getInstance() {
return ourInstance;
}
To give an idea of what I am doing. I have a Main activity that allows you to add names to a recyclerView then start a round that sends to an Arraylist of people through an Intent to CurrentMatchActivity. after a while of user input it launches another instance of CurrentMatchActivity by passing an Arraylist of people to a new CurrentMatchActivity.
Here is the Person class
public class Person implements Parcelable {
private String name;
private int wins;
private long totalWins;
private boolean stillPlaying;
private ArrayList<Person> previousOpponents;
Person(String name)
{
this.name = name;
wins = 0;
totalWins = 0;
stillPlaying = true;
previousOpponents = new ArrayList<>();
}
public void setStillPlaying(boolean playing)
{
stillPlaying = playing;
}
public void addOpponent(Person person) {
previousOpponents.add(person);
}
public boolean hasFought(Person person) {
return previousOpponents.contains(person);
}
#Override
public int describeContents() {
return 0;
}
private Person(Parcel in)
{
name = in.readString();
wins = in.readInt();
totalWins = in.readLong();
stillPlaying = (boolean) in.readValue(null);
previousOpponents = new ArrayList<>();
in.readTypedList(previousOpponents, null);
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(wins);
dest.writeLong(totalWins);
dest.writeValue(stillPlaying);
dest.writeTypedList(previousOpponents);
}
public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
public Person createFromParcel(Parcel in) {
return new Person(in);
}
public Person[] newArray(int size) {
return new Person[size];
}
};
}
Here is the CurrentMatchActivity
package omarzious.myapplication;
public class CurrentMatchActivity extends Activity {
private ArrayList<Person> people;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private int round;
private RetainedFragment dataFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current_match);
FragmentManager fm = getFragmentManager();
dataFragment = (RetainedFragment) fm.findFragmentByTag("currentMatchData");
if (dataFragment == null){
dataFragment = new RetainedFragment();
fm.beginTransaction().add(dataFragment, "currentMatchData").commit();
round = getIntent().getIntExtra("round",1);
people = getIntent().getParcelableArrayListExtra("people");
prepareMatch();
}
else
{
people = dataFragment.getData();
}
this.setTitle(getString(R.string.round)+" "+round);
mRecyclerView = (RecyclerView) findViewById(R.id.current_match_recycler_view);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new CurrentMatchAdapter(people, getApplicationContext());
mRecyclerView.setAdapter(mAdapter);
// Swipe Portion
SwipeableRecyclerViewTouchListener swipeTouchListener = new SwipeableRecyclerViewTouchListener(mRecyclerView,
new SwipeableRecyclerViewTouchListener.SwipeListener() {
private int personIndex;
#Override
public boolean canSwipe(int position)
{
if (position == (int)people.size()/2)
{
return false;
}
return people.get(position*2).isStillPlaying();
}
#Override
public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions)
{
personIndex = position*2;
//personBeat(personIndex, personIndex+1);
people.get(personIndex).won();
mAdapter.notifyItemChanged(position);
// if player on right won
if (people.get(personIndex).isWinner())
{
people.get(personIndex).setStillPlaying(false);
people.get(personIndex+1).setStillPlaying(false);
if (checkForRoundEnd())
{
startNewRound();
}
}
}
mAdapter.notifyDataSetChanged();
}
public void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
personIndex = position*2+1;
people.get(personIndex).won();
mAdapter.notifyItemChanged(personIndex);
// if player on left won
if (people.get(personIndex).isWinner())
{
people.get(personIndex).setStillPlaying(false);
people.get(personIndex-1).setStillPlaying(false);
if (checkForRoundEnd())
{
startNewRound();
}
}
}
mAdapter.notifyDataSetChanged();
}
});
mRecyclerView.addOnItemTouchListener(swipeTouchListener);
}
public void checkForRematches()
{
int i = 0;
Person personA;
Person personB;
ListIterator<Person> a;
boolean collision = false;
int numberOfItterations = 0;
// do {
a = people.listIterator();
collision = false;
i=0;
while ( i < (int)(people.size() / 2))
{
personA = a.next();
personB = a.next();
i++;
if (personA.hasFought(personB)) {
a.remove();
a.add(personB);
people.add(personB);
collision = true;
Toast.makeText(this,"WTF", Toast.LENGTH_SHORT);
}
}
numberOfItterations++;
// } while(collision);
Toast.makeText(this, "prepare match had to itterate "+numberOfItterations+ "times", Toast.LENGTH_SHORT).show();
}
public void prepareMatch() {
Collections.shuffle(people);
int i = 0;
Person personA;
Person personB;
ListIterator<Person> a = people.listIterator();
if (round > 1)
{
// checkForRematches();
}
while (i < (int)(people.size() / 2))
{
personA = a.next();
personB = a.next();
i++;
personA.addOpponent(personB);
personB.addOpponent(personA);
}
}
public boolean checkForRoundEnd()
{
int stillPlayingAllowed = people.size() % 2;
int peopleStillPlaying = 0;
for (Person person : people) {
if (person.isStillPlaying()) {
peopleStillPlaying++;
}
}
return peopleStillPlaying == stillPlayingAllowed;
}
public void startNewRound()
{
Iterator<Person> i = people.iterator();
Person person;
while (i.hasNext()) {
person = i.next();
if (!person.isWinner() && !person.isStillPlaying())
{
i.remove();
}
person.clearWins();
person.setStillPlaying(true);
}
if (people.size() > 1) {
Toast.makeText(this, "Starting new round", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, CurrentMatchActivity.class);
intent.putExtra("round",++round);
intent.putParcelableArrayListExtra("people", people);
startActivity(intent);
}
else
{
Intent intent = new Intent(this, GameOverActivity.class);
intent.putParcelableArrayListExtra("people", people);
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_current_match, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDestroy()
{
super.onDestroy();
dataFragment.setData(people);
}
}
now the odd part is it works fine. unless I activate the code.
public void prepareMatch() {
Collections.shuffle(people);
int i = 0;
Person personA;
Person personB;
ListIterator<Person> a;
while (i < (int)(people.size() / 2))
{
personA = a.next();
personB = a.next();
i++;
personA.addOpponent(personB);
personB.addOpponent(personA);
}
}
which causes a null pointer crash in the MainAdapter
The mainActivity uses the mainAdapter. but the currentMatchActivity uses a CurrentMatch adapter.. And the crash happens when it tries to create an CurrentMatchActivity from the CurrentMatchActivity.
I don't believe that MainAdapter should even be in use here... only CurrentMatchAdapter. Furthermore... I don't see how activating the prepareMatch function should affect the flow of my code in that way..
Edit: found out that it was crashing because of because of the parcelable. Guess it didn't like a person list inside of a person list.
I came to the conclusion that the issue was nesting an arraylist of a class inside an arraylist of the same class and making it parcelable. I ended up using an arraylist of int primary keys inside of the class and it fixed the issue.
Example:
class A implements parcelable {
arraylist<int> keys;
}
arraylist<a>
Im having an issue with getting data that is obtained when my listadapter is set to my listview. Im trying to get this data in onItemClick so that i can put it into my intent extra's for my other activity to obtain.
The Problem
Currently i've created null string variables and then in my adapter assigning the strings with the desired text by methods within my model. However the problem im having is that the text that is being pulled is not the correct text for the position that onitemclick was called for.
Here some code...
XMLParseActivity
public class XMLParseActivity extends Activity implements AdapterView.OnItemClickListener {
private ListView mIssueListView;
private IssueParser mIssueParser;
private List<IssueFeed> mIssueList;
private IssueAdapter mIssueAdapter;
private String result_connectedtype = "";
private String result_symptom = "";
private String result_problem = "";
private String result_solution = "";
private String result_comments = "";
...
public class IssueAdapter extends ArrayAdapter<IssueFeed> {
public List<IssueFeed> issueFeedList;
public IssueAdapter(Context context, int textViewResourceId, List<IssueFeed> issueFeedList) {
super(context, textViewResourceId, issueFeedList);
this.issueFeedList = issueFeedList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
IssueHolder issueHolder = null;
if (convertView == null) {
view = View.inflate(XMLParseActivity.this, R.layout.issue_list_item, null);
issueHolder = new IssueHolder();
issueHolder.issueConnectedType = (TextView) view.findViewById(R.id.result_connected_type);
issueHolder.issueSymptomView = (TextView) view.findViewById(R.id.result_symptom);
view.setTag(issueHolder);
} else {
issueHolder = (IssueHolder) view.getTag();
}
IssueFeed issueFeed = issueFeedList.get(position);
issueHolder.issueConnectedType.setText(issueFeed.getConnected_type());
issueHolder.issueSymptomView.setText(issueFeed.getSymptom());
//THE DATA I WANT TO USE IN MY INTENT
result_solution = issueFeed.getSolution();
result_comments = issueFeed.getComments();
result_connectedtype = issueFeed.getConnected_type();
result_problem = issueFeed.getProblem();
result_symptom = issueFeed.getSymptom();
return view;
}
}
static class IssueHolder {
public TextView issueSymptomView;
public TextView issueConnectedType;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int position, long id) {
//Put the strings in intent extra
Intent intent = new Intent(this, SpecificIssueActivity.class);
intent.putExtra("symptom", result_symptom);
intent.putExtra("problem", result_problem);
intent.putExtra("solution", result_solution);
intent.putExtra("comments", result_comments);
intent.putExtra("connectedtype", result_connectedtype);
startActivity(intent);
}
The listAdapter is set in a asynctask in the below code
public class DoLocalParse extends AsyncTask<String, Void, List<IssueFeed>> {
ProgressDialog prog;
String jsonStr = null;
Handler innerHandler;
#Override
protected void onPreExecute() {
prog = new ProgressDialog(XMLParseActivity.this);
prog.setMessage("Loading....");
prog.show();
}
#Override
protected List<IssueFeed> doInBackground(String... params) {
mIssueParser = new IssueParser(null);
mIssueList = mIssueParser.parseLocally(params[0]);
return mIssueList;
}
#Override
protected void onPostExecute(List<IssueFeed> result) {
prog.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
mIssueAdapter = new IssueAdapter(XMLParseActivity.this, R.layout.issue_list_item,
mIssueList);
int count = mIssueAdapter.getCount();
if (count != 0 && mIssueAdapter != null) {
mIssueListView.setAdapter(mIssueAdapter);
}
}
});
}
}
And my model IssueFeed looks like this
public class IssueFeed implements Serializable {
private String connected_type;
private String symptom;
private String problem;
private String solution;
private String comments;
public IssueFeed() {
}
public IssueFeed(String connected_type, String symptom, String problem, String solution, String comments) {
this.connected_type = connected_type;
this.symptom = symptom;
this.problem = problem;
this.solution = solution;
this.comments = comments;
}
public String getConnected_type() {
return connected_type;
}
public String getSymptom() {
return symptom;
}
public String getProblem() {
return problem;
}
public String getSolution() {
return solution;
}
public String getComments() {
return comments;
}
public void setConnected_type(String connected_type) {
this.connected_type = connected_type;
}
public void setSymptom(String symptom) {
this.symptom = symptom;
}
public void setProblem(String problem) {
this.problem = problem;
}
public void setSolution(String solution) {
this.solution = solution;
}
public void setComments(String comments) {
this.comments = comments;
}
}
I have solve the issue by getting the data from some simple methods in my model to obtain the values.