chatMessages = new ArrayList<>();
listView = findViewById(R.id.list_of_messages);
Message(topic_id);
listView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
listView.setAdapter(chatAdapter);
buttonSend = findViewById(R.id.send);
fileSend = findViewById(R.id.file_send);
chatText = (EditText) findViewById(R.id.mychat);
// delete_btn = findViewById(R.id.);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
// View select;
#Override
public boolean onItemLongClick(AdapterView<?> parent, final View view, final int position, long id) {
if ( view != null){
view.setBackgroundColor(0xFFB2DFDB);
}
String value = (String) listView.getItemAtPosition(position);
msgid = chatMessages.get(position).getMessageID();
message = chatMessages.get(position).getMessageText();
userid1 = chatMessages.get(position).getUserId();
username = chatMessages.get(position).getMessageUser();
replyuser = chatMessages.get(position).getReply_user();
if (sno.equals(userid1)) {
view.setBackgroundColor(0xFFB2DFDB);
// Toast.makeText(getApplicationContext(),"Hello"+userid1+msgid,Toast.LENGTH_SHORT).show();
// ImageView edit = (ImageView) findViewById(R.id.delete_icon);
// edit.setVisibility(View.VISIBLE);
// );
topic.setText(getString(R.string.edit));
myToolbar.setLogo(R.drawable.edit);
// view.setBackgroundColor(Color.WHITE);
topic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chatMessages.remove(position);
view.setBackgroundColor(Color.TRANSPARENT);
userid1 = null;
chatAdapter.notifyDataSetChanged();
chatText.setText(message);
}
});
myToolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chatMessages.remove(position);
userid1 = null;
chatAdapter.notifyDataSetChanged();
chatText.setText(message);
}
});
} else {
view.setBackgroundColor(0xFFB2DFDB);
// Toast.makeText(getApplicationContext(),"Hello"+userid1+msgid,Toast.LENGTH_SHORT).show();
topic.setText(getString(R.string.reply));
myToolbar.setLogo(R.drawable.replay);
// view.setBackgroundColor(Color.WHITE);
// reply = (ImageView) findViewById(R.id.reply_icon);
// reply.setVisibility(View.VISIBLE);
topic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
replylayout = (LinearLayout) findViewById(R.id.reply_layout);
replylayout.setVisibility(View.VISIBLE);
TextView replay_name = (TextView) findViewById(R.id.reply_user);
TextView replay_text = (TextView) findViewById(R.id.reply_text);
ImageButton cancell = (ImageButton) findViewById(R.id.cancell_btn);
replay_name.setText(username);
replay_text.setText(message);
cancell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
replylayout.removeAllViews();
startActivity(getIntent());
}
});
}
});
myToolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
replylayout = (LinearLayout) findViewById(R.id.reply_layout);
replylayout.setVisibility(View.VISIBLE);
TextView replay_name = (TextView) findViewById(R.id.reply_user);
TextView replay_text = (TextView) findViewById(R.id.reply_text);
ImageButton cancell = (ImageButton) findViewById(R.id.cancell_btn);
replay_name.setText(username);
replay_text.setText(message);
cancell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
replylayout.removeAllViews();
startActivity(getIntent());
}
});
}
});
}
return true;
}
});
I want to implement setOnItemLongClickListener on list view when long press on list item then perform other activity like delete and edit functionality. when press long click then give error cannot be cast to java.lang.String
Replace your code with this
String value = (String) listView.getItemAtPosition(position);
With This
String value = String.valueOf(listView.getItemAtPosition(position));
The main problem is in this line
String value = (String) listView.getItemAtPosition(position);
I definitely not sure that your listview is filled with String items as later in the code you call
chatMessages.get(position).getMessageID()
So your value should be something like
ChatMessage value = (ChatMessage) listView.getItemAtPosition(position);
And in your adapter you need to change these methods (if they are not changed already):
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
String value = (String) listView.getItemAtPosition(position);
View cant be cast into string. I think above code should be (presume the item content on your list view is text):
String value = listView.getItemAtPosition(position).toString();
Related
I have an activity which is connected with an adapter. In the activity, I include adapter layout. when I click on the button than adapter layout open but when I press back button in adapter layout than automatically reached main activity. I want that when I press back button in adapter than go to previous activity.
activity code is below
public class TestFragment extends Fragment {
private Button btnA,
btnB,
btnC,
btnD,
btnSubmit,
btnNext,
btnPrev,
btnFlag;
private TextView tvQuestion,
tvLayout;
private int totalItem;
private int listItem = 0;
private ArrayList < mcqQuestion > quesList = new ArrayList < >();
private int score = 0;
private boolean isLoading = true;
private RelativeLayout rlMcqProgress;
private FirebaseAuth mAuth;
private boolean allAnswered = false;
private RecyclerView rvQuesLayout;
private RecyclerView.LayoutManager layoutManager;
private QuestionLayoutRecyclerAdapter adapter;
private LinearLayout llQuestionAll;
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference myRef = database.getReference("tax").child("Questions");
public TestFragment() {
// 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_test, container, false);
btnA = view.findViewById(R.id.btn_mcq_A);
btnB = view.findViewById(R.id.btn_mcq_B);
btnC = view.findViewById(R.id.btn_mcq_C);
btnD = view.findViewById(R.id.btn_mcq_D);
btnSubmit = view.findViewById(R.id.btn_mcq_submit);
btnNext = view.findViewById(R.id.btn_mcq_next);
btnPrev = view.findViewById(R.id.btn_mcq_prev);
btnFlag = view.findViewById(R.id.btn_mcq_flag);
tvQuestion = view.findViewById(R.id.tv_mcq_question);
tvLayout = view.findViewById(R.id.tv_mcq_question_layout);
rvQuesLayout = view.findViewById(R.id.rv_layout_question_test);
rlMcqProgress = view.findViewById(R.id.rl_mcq_progress);
rlMcqProgress.setVisibility(View.VISIBLE);
llQuestionAll = view.findViewById(R.id.ll_test_all);
mAuth = FirebaseAuth.getInstance();
getFData();
btnA.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
quesList.get(listItem).setSelAnswer("optA");
setButtonColor();
btnA.setBackgroundResource(R.color.sky_blue);
}
});
btnB.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
quesList.get(listItem).setSelAnswer("optB");
setButtonColor();
btnB.setBackgroundResource(R.color.sky_blue);
}
});
btnC.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
quesList.get(listItem).setSelAnswer("optC");
setButtonColor();
btnC.setBackgroundResource(R.color.sky_blue);
}
});
btnD.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
quesList.get(listItem).setSelAnswer("optD");
setButtonColor();
btnD.setBackgroundResource(R.color.sky_blue);
}
});
btnFlag.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
setFlagValue();
setFlagColor();
}
});
tvLayout.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
adapter.notifyDataSetChanged();
if (rvQuesLayout.getVisibility() == View.GONE || rvQuesLayout.getVisibility() == View.INVISIBLE) {
rvQuesLayout.setVisibility(View.VISIBLE);
llQuestionAll.setVisibility(View.GONE);
} else {
rvQuesLayout.setVisibility(View.GONE);
llQuestionAll.setVisibility(View.VISIBLE);
}
}
});
btnNext.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
displayNextQues();
}
});
btnPrev.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
displayPrevQues();
}
});
btnSubmit.setOnClickListener(new View.OnClickListener() {#SuppressLint("SetTextI18n")#Override
public void onClick(View v) {
for (int i = 0; i < totalItem; i++) {
if (quesList.get(i).getSelAnswer().equals("none")) {
allAnswered = false;
score++;
break;
} else {
if (quesList.get(i).getSelAnswer().equals(quesList.get(i).getAnswer())) {
score++;
}
allAnswered = true;
}
}
if (allAnswered) {
Intent intent = new Intent(this, finalresult.class);
intent.putExtra("score", score);
intent.putExtra("questions", totalItem);
startActivity(intent);
} else {
Toast.makeText(this, "Answer all the questions", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
private void makeRecyclerView() {
layoutManager = new LinearLayoutManager(this);
//rvQuesLayout.setHasFixedSize(true);
rvQuesLayout.setLayoutManager(layoutManager);
adapter = new QuestionLayoutRecyclerAdapter(quesList);
rvQuesLayout.setAdapter(adapter);
adapter.setOnItemClickListner(new QuestionLayoutRecyclerAdapter.onItemClickListner() {#Override
public void onClick(int pos) {
listItem = pos;
if (listItem >= 0 && listItem < totalItem) {
makeAllDisplay();
rvQuesLayout.setVisibility(View.GONE);
llQuestionAll.setVisibility(View.VISIBLE);
}
}
});
}
private void setDisplay(int item) {
btnA.setText(quesList.get(item).getOptA());
btnB.setText(quesList.get(item).getOptB());
btnC.setText(quesList.get(item).getOptC());
btnD.setText(quesList.get(item).getOptD());
tvQuestion.setText(quesList.get(item).getQuestion());
}
private void getFData() {
myRef.addValueEventListener(new ValueEventListener() {#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) {
String qtext = (String) messageSnapshot.child("qText").getValue();
String optA = (String) messageSnapshot.child("optA").getValue();
String optB = (String) messageSnapshot.child("optB").getValue();
String optC = (String) messageSnapshot.child("optC").getValue();
String optD = (String) messageSnapshot.child("optD").getValue();
String answer = (String) messageSnapshot.child("answer").getValue();
quesList.add(new mcqQuestion(qtext, optA, optB, optC, optD, answer, "none", false));
Log.d("TOTAL ITEM", String.valueOf(quesList.size()));
}
totalItem = quesList.size();
isLoading = false;
if (!isLoading) {
setDisplay(listItem);
rlMcqProgress.setVisibility(View.GONE);
tvLayout.setVisibility(View.VISIBLE);
}
makeRecyclerView();
}#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void setFlagValue() {
if (quesList.get(listItem).isFlag()) {
quesList.get(listItem).setFlag(false);
} else {
quesList.get(listItem).setFlag(true);
}
}
private void setFlagColor() {
if (quesList.get(listItem).isFlag()) {
btnFlag.setBackgroundColor(ContextCompat.getColor(Objects.requireNonNull(this), R.color.black));
btnFlag.setTextColor(ContextCompat.getColor(Objects.requireNonNull(this), R.color.grey));
} else {
btnFlag.setBackgroundColor(ContextCompat.getColor(Objects.requireNonNull(this), R.color.grey_light));
btnFlag.setTextColor(ContextCompat.getColor(Objects.requireNonNull(this), R.color.grey));
}
}
private void setButtonColor() {
btnA.setBackgroundResource(R.color.grey_light);
btnB.setBackgroundResource(R.color.grey_light);
btnC.setBackgroundResource(R.color.grey_light);
btnD.setBackgroundResource(R.color.grey_light);
}
private void displayNextQues() {
if (listItem < totalItem - 1) {
listItem++;
makeAllDisplay();
} else {
btnNext.setVisibility(View.GONE);
btnSubmit.setVisibility(View.VISIBLE);
}
}
private void makeAllDisplay() {
setDisplay(listItem);
setButtonColor();
setFlagColor();
switch (quesList.get(listItem).getSelAnswer()) {
case "optA":
btnA.setBackgroundResource(R.color.sky_blue);
break;
case "optB":
btnB.setBackgroundResource(R.color.sky_blue);
break;
case "optC":
btnC.setBackgroundResource(R.color.sky_blue);
break;
case "optD":
btnD.setBackgroundResource(R.color.sky_blue);
break;
default:
setButtonColor();
break;
}
}
private void displayPrevQues() {
btnNext.setVisibility(View.VISIBLE);
if (listItem > 0 && listItem < totalItem) {
listItem--;
makeAllDisplay();
} else {
Toast.makeText(this, "Cannot GO back!!", Toast.LENGTH_SHORT).show();
}
}
}
and the adapter code is below
public class QuestionLayoutRecyclerAdapter extends RecyclerView.Adapter < QuestionLayoutRecyclerAdapter.FlagViewHolder > {
private ArrayList < mcqQuestion > quesList;
private onItemClickListner onItemClickListner;
public void setOnItemClickListner(QuestionLayoutRecyclerAdapter.onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner {
void onClick(int pos); //pass your object types.
}
public QuestionLayoutRecyclerAdapter(ArrayList < mcqQuestion > quesList) {
this.quesList = quesList;
}
#NonNull#Override
public FlagViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(layout.question_layout, parent, false);
FlagViewHolder flagViewHolder = new FlagViewHolder(view, quesList);
return flagViewHolder;
}
#SuppressLint("ResourceAsColor")#Override
public void onBindViewHolder(#NonNull final FlagViewHolder holder, int position) {
mcqQuestion question_id = quesList.get(position);
holder.tvQuestionNumber.setText("Question " + (position + 1));
if (question_id.isFlag()) {
holder.ivFlag.setImageResource(drawable.right2);
} else {
holder.ivFlag.setImageResource(drawable.white2);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
onItemClickListner.onClick(holder.getAdapterPosition());
}
});
}
#Override
public int getItemCount() {
return quesList.size();
}
public static class FlagViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView ivFlag;
TextView tvQuestionNumber;
ArrayList < mcqQuestion > quesList;
public FlagViewHolder(#NonNull View itemView, ArrayList < mcqQuestion > quesList) {
super(itemView);
ivFlag = itemView.findViewById(id.iv_layout_flag);
tvQuestionNumber = itemView.findViewById(id.tv_layout_question_number);
itemView.setOnClickListener(this);
this.quesList = quesList;
}
#Override
public void onClick(View v) {
int quesClick = getAdapterPosition();
}
}
}
Try this
#Override
public void onBackPressed()
{
Intent intent = new Intent(this, ActivityWhereYouWantToGo.class);
startActivity(intent);
}
As per you code, you are not navigation to another screen you are only changing the Visibility. On back press, you can check which view is currently displaying and handle accordingly.
#Override
public void onBackPressed() {
if (findViewById(R.id.your_view).visibility == View.Visible) {
//change your visibility
rvQuesLayout.setVisibility(View.VISIBLE);
llQuestionAll.setVisibility(View.GONE);
//reverse the things you did in makeAllDisplay() method
} else {
super.onBackPressed();
}
}
When I run my app and go to the "EditProfile" activity. And then, I will immediately receive the toast message "Something is wrong" which means, the variables "selectedCountry", "selectedAge", and "selectedGender" are null.
public class EditProfile extends AppCompatActivity {
UserInfo userInfo;
UserInfo profileDetails;
Spinner spinnerFrom;
Spinner spinnerAge;
Spinner spinnerGender;
EditText hobbyEdit;
Button btnDone;
TextView textView;
String selectedCountry;
String selectedAge;
String selectedGender;
DatabaseHelper mydb = new DatabaseHelper(this, "MyUsers", null, 5);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Profile.class);
intent.putExtra("id", userInfo.getId());
intent.putExtra("username", userInfo.getUsername());
startActivity(intent);
}
});
Bundle extras = getIntent().getExtras();
int id = extras.getInt("id");
final String username = extras.getString("username");
// Username
userInfo = new UserInfo(id, username);
textView = (TextView) findViewById(R.id.usernameUnedit);
textView.setText(username);
// Country
spinnerFrom = (Spinner) findViewById(R.id.spinnerFrom);
Locale[] locales = Locale.getAvailableLocales();
final ArrayList<String> countries = new ArrayList<String>();
countries.add("-");
for (Locale locale : locales) {
String country = locale.getDisplayCountry();
if (country.trim().length() > 0 && !countries.contains(country)) {
countries.add(country);
}
}
Collections.sort(countries);
ArrayAdapter<String> countryAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, countries);
countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerFrom.setAdapter(countryAdapter);
spinnerFrom.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedCountry = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Age
spinnerAge = (Spinner) findViewById(R.id.spinnerAge);
final ArrayList<String> ages = new ArrayList<String>();
ages.add("-");
for (int i = 18; i < 100; i++) {
ages.add(String.valueOf(i));
}
ArrayAdapter<String> ageAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ages);
ageAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerAge.setAdapter(ageAdapter);
spinnerAge.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedAge = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Gender
spinnerGender = (Spinner) findViewById(R.id.spinnerGender);
final ArrayList<String> genders = new ArrayList<String>();
genders.add("-");
genders.add("Male ♂");
genders.add("Female ♀");
genders.add("Other");
ArrayAdapter<String> genderAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, genders);
genderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGender.setAdapter(genderAdapter);
spinnerGender.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedGender = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Hobby
hobbyEdit = (EditText) findViewById(R.id.hobbyEdit);
// Button done
btnDone = (Button) findViewById(R.id.btnDone);
btnDone.setEnabled(false);
/* Stuck at this if statement below */
if (selectedCountry != null && selectedAge != null && selectedGender != null) {
if (!mydb.isStoredProfileDetails(username, selectedCountry, selectedAge, selectedGender, hobbyEdit.getText().toString())) {
btnDone.setEnabled(true);
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
profileDetails = new UserInfo(selectedCountry, selectedAge, selectedGender, hobbyEdit.getText().toString());
mydb.updateTable(username, profileDetails);
}
});
} else {
Toast.makeText(this, "Something is wrong 2.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "Something is wrong.", Toast.LENGTH_LONG).show();
}
}
}
I expect that after choosing an item from those 3 dropdown lists (spinners) and the values of the chosen items do not exist in database, then the "Done" button would be clickable. Once the button is clicked, it would store the selected values from the dropdown lists (spinners) into database by updating it.
Unfortunately, I am stuck at the if statement as stated in the given code as it keeps returning the "else" statement.
Set your variable as...
String selectedCountry = "";
String selectedAge = "";
String selectedGender = "";
And check condition as...
if (!selectedCountry.equals("") && !selectedAge.equals("") && !selectedGender.equals("")) {
//your code goes here
}
You have to check your both conditions in Spinner's OnItemSelectedListener, If both conditions will return true then enable your button. and call setonClickListener on button in onCreateView, like this.
spinnerGender.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedGender = parent.getItemAtPosition(position).toString();
//Conditions to enable button
if (selectedCountry != null && selectedAge != null && selectedGender != null) {
if (!mydb.isStoredProfileDetails(username, selectedCountry, selectedAge, selectedGender, hobbyEdit.getText().toString())) {
btnDone.setEnabled(true);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
add these lines in all spinners.
In your onCreate method, you have instantiated the views and attached listeners to them. That is perfectly fine. However, this does not mean that the logic in those listeners will be execute at the same time and order. You have just defined the behaviour of the listeners. After all that initialisation, your code directly checks the values of the three Strings mentioned in your question. It does not wait for a user to interact with the spinners.
What you want is to trigger the change in the "done" button when a user selects something from the spinner. So the logic of setting the strings and thereby checking if you could enable the "done" button must go in the listeners of the spinners.
I am not giving you a direct code solution to the problem, but an approach which you could employ.
In my HomeActivity I have a ButtonNavigationView with 4 items with fragments, in one of them ( fragments ) I have a button that adds dynamic views into a linear layout I want them to not disappear when I switch to another tab on ButtonNavigationView
As you can see in first image, I added some Dynamic views by clicking on the buttons
and then in second image I switched to another tab on ButtonNavigationView
after that in third image when I go back on second tab, dynamic generated views are all gone, what can I do to save them ?
HomeActivity
private TextView mTextMessage;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
selectedFragment = new FactorsFragment();
break;
case R.id.navigation_dashboard:
selectedFragment = new NewFactorFragment();
break;
case R.id.navigation_notifications:
selectedFragment = new ProductsFragment();
break;
case R.id.navigation_checklist:
selectedFragment = new CheckList();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,selectedFragment).commit();
return true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
navigation.setSelectedItemId(R.id.navigation_dashboard);
SQLiteStudioService.instance().start(this);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new NewFactorFragment());
}
#Override
protected void onDestroy() {
SQLiteStudioService.instance().stop();
super.onDestroy();
}
Fragment that i need to save changes
public View onCreateView(#NonNull final LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_newfactor, container, false);
ln = v.findViewById(R.id.itemsContainer);
submit = v.findViewById(R.id.submit);
editText2 = v.findViewById(R.id.customerName);
setRetainInstance(true);
dbConnector = new DbConnector(getContext(), null, null, 1);
Cursor c = dbConnector.get().rawQuery("SELECT * FROM categories", null);
while (c.moveToNext()) {
final int id = c.getInt(c.getColumnIndex("id"));
String name = c.getString(c.getColumnIndex("name"));
final View rowView = inflater.inflate(R.layout.field_button, null);
Button fieldCreator = rowView.findViewById(R.id.fieldCreator);
fieldContainer = rowView.findViewById(R.id.field_container);
fieldCreator.setText(name);
fieldCreator.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout fieldContainer = ((RelativeLayout) v.getParent()).findViewById(R.id.field_container);
fieldContainer.removeAllViews();
final Cursor c = dbConnector.get().rawQuery("SELECT * FROM product WHERE category_id = " + id, null);
while (c.moveToNext()) {
final View rowView = inflater.inflate(R.layout.field, null);
TextView productName = rowView.findViewById(R.id.product_name);
final EditText editText = rowView.findViewById(R.id.number);
Button add = rowView.findViewById(R.id.add);
Button remove = rowView.findViewById(R.id.remove);
final TextView productPrice = rowView.findViewById(R.id.product_price);
productName.setText(c.getString(c.getColumnIndex("name")));
final int price_db = Integer.parseInt(c.getString(c.getColumnIndex("price")));
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (!editText.getText().toString().equals("")) {
int price = Integer.parseInt(editText.getText().toString()) * price_db;
productPrice.setText(price + "");
}
}
});
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int num = Integer.parseInt(editText.getText().toString());
int num_num = num + 1;
editText.setText(num_num + "");
}
});
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int num = Integer.parseInt(editText.getText().toString());
if (num > 0) {
int num_num = num - 1;
editText.setText(num_num + "");
}
}
});
fieldContainer.addView(rowView);
}
}
});
ln.addView(rowView);
}
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < ln.getChildCount(); i++) {
RelativeLayout button = (RelativeLayout) ln.getChildAt(i);
LinearLayout itemCon = (LinearLayout) button.getChildAt(1);
for (int o = 0; o < itemCon.getChildCount(); o++) {
JSONObject jsonObject = new JSONObject();
LinearLayout field = (LinearLayout) itemCon.getChildAt(o);
EditText number = (EditText) field.getChildAt(2);
TextView price = (TextView) field.getChildAt(0);
TextView name = (TextView) field.getChildAt(3);
if (!number.getText().toString().equals("0")) {
try {
jsonObject.put("product_name", name.getText());
jsonObject.put("number", number.getText());
jsonObject.put("price", price.getText());
jsonObject.put("buyer_name",editText2.getEditText().getText().toString());
} catch (JSONException e) {
}
}
jsonArray.put(jsonObject);
}
}
ContentValues values = new ContentValues();
values.put("name",editText2.getEditText().getText().toString());
values.put("items",jsonArray.toString());
Log.e("JSONobject",jsonArray.toString());
try {
long id = dbConnector.get().insert("factors",null,values);
}catch (SQLiteException exception){
Log.e("ERROR",exception.getMessage());
}
}
});
return v;
}
I had this working in the past, but I made some changes to my code and now, whenever I delete a row from the ListView and click on one of the remaining rows, I am getting IndexOutOfBoundsException: Index: 1, Size: 1.
This only seems to be happening when there is a single row remaining. If there are more than one row remain, this error does not appear.
The image above shows that the when there are more than one row remaining the error does not occur.
I am not sure why this would be happening since none of the code for selecting and deleting a row has changed.
I have checked other posts on this site but none of them seem to be similar to what I am experiencing.
Android IndexOutOfBoundsException: Index: 1, Size: 1
OutOfBoundException index:1, size:1
java jtable removeRow : java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
I have posted my code below.
Logcat:
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.get(ArrayList.java:411)
at ca.rvogl.tpbcui.views.LeagueAdapter$2.onClick(LeagueAdapter.java:116)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Code for selecting a row in the listview:
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
League league = leaguesList.get(position);
int id = league.getId();
String leagueId = String.valueOf(id);
holder.id.setText(leagueId);
holder.name.setText(league.getName());
holder.basescore.setText(league.getBaseScore());
holder.basescorepercentage.setText(league.getBaseScorePercentage());
if (league.getAverage() != "") {
holder.leagueAverage.setText(String.format("League Avg: %s", league.getAverage()));
} else {
holder.leagueAverage.setText(String.format("League Avg: %s", "0"));
}
//Formatting And Displaying Timestamp
holder.timestamp.setText(formatDate(league.getTimestamp()));
holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//creating a popup menu
PopupMenu popup = new PopupMenu(context, holder.buttonViewOption);
//inflating menu from xml resource
popup.inflate(R.menu.league_options_menu);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.profile:
((MainActivity) context).showLeagueDialog(true, leaguesList.get(position), position);
break;
case R.id.delete:
((MainActivity) context).deleteLeague(position);
break;
}
return false;
}
});
//displaying the popup
popup.show();
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int leagueId = leaguesList.get(position).getId();
Intent myIntent = new Intent(context, BowlerActivity.class);
myIntent.putExtra("leagueId", leagueId);
context.startActivity(myIntent);
}
});
}
Code for deleting a row:
//Deleting League From SQLite Database And Removing The League Item From The List By Its Position
public void deleteLeague(int position) {
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "Series will be deleted.", Snackbar.LENGTH_LONG)
.setActionTextColor(Color.YELLOW)
.setAction("OK", new View.OnClickListener() {
#Override
public void onClick(View v) {
//Deleting The League From The Database
db.deleteLeague(leaguesList.get(position));
//Removing League From The List
leaguesList.remove(position);
mAdapter.notifyItemRemoved(position);
toggleEmptyLeagues();
}
});
snackbar.show();
}
The error seems to be happening with this line int leagueId = leaguesList.get(position).getId();
Any help getting this error fixed would be greatly appreciated.
BowlerActivity.java
public class BowlerActivity extends AppCompatActivity {
private BowlerAdapter mAdapter;
private final List<Bowler> bowlersList = new ArrayList<>();
private TextView noBowlersView;
private DatabaseHelper db;
private TextView leagueId;
private String savedLeagueId;
private TextView seriesleagueId;
private String seriesLeagueId;
private TextView bowlerAverage;
private TextView bowlerHandicap;
private String savedBowlerAverage;
private static final String PREFS_NAME = "prefs";
private static final String PREF_BLUE_THEME = "blue_theme";
private static final String PREF_GREEN_THEME = "green_theme";
private static final String PREF_ORANGE_THEME = "purple_theme";
private static final String PREF_RED_THEME = "red_theme";
private static final String PREF_YELLOW_THEME = "yellow_theme";
#Override protected void onResume() {
super.onResume();
db = new DatabaseHelper( this );
mAdapter.notifyDatasetChanged( db.getAllBowlers( savedLeagueId ) );
}
#Override
protected void onCreate(Bundle savedInstanceState) {
//Use Chosen Theme
SharedPreferences preferences = getSharedPreferences( PREFS_NAME, MODE_PRIVATE );
boolean useBlueTheme = preferences.getBoolean( PREF_BLUE_THEME, false );
if (useBlueTheme) {
setTheme( R.style.AppTheme_Blue_NoActionBar );
}
boolean useGreenTheme = preferences.getBoolean( PREF_GREEN_THEME, false );
if (useGreenTheme) {
setTheme( R.style.AppTheme_Green_NoActionBar );
}
boolean useOrangeTheme = preferences.getBoolean( PREF_ORANGE_THEME, false );
if (useOrangeTheme) {
setTheme( R.style.AppTheme_Orange_NoActionBar );
}
boolean useRedTheme = preferences.getBoolean( PREF_RED_THEME, false );
if (useRedTheme) {
setTheme( R.style.AppTheme_Red_NoActionBar );
}
boolean useYellowTheme = preferences.getBoolean( PREF_YELLOW_THEME, false );
if (useYellowTheme) {
setTheme( R.style.AppTheme_Yellow_NoActionBar );
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bowler);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull( getSupportActionBar() ).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
overridePendingTransition(0, 0);
}
});
savedLeagueId = String.valueOf(getIntent().getIntExtra("leagueId",2));
leagueId = findViewById(R.id.tvLeagueId);
bowlerAverage = (TextView) findViewById(R.id.tvBowlerAverage);
bowlerHandicap = (TextView) findViewById(R.id.tvBowlerHandicap);
CoordinatorLayout coordinatorLayout = findViewById( R.id.coordinator_layout );
RecyclerView recyclerView = findViewById( R.id.recycler_view );
noBowlersView = findViewById(R.id.empty_bowlers_view);
db = new DatabaseHelper(this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.add_bowler_fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showBowlerDialog(false, null, -1);
}
});
mAdapter = new BowlerAdapter(this, bowlersList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
//recyclerView.addItemDecoration(new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, 16));
recyclerView.setAdapter(mAdapter);
toggleEmptyBowlers();
}
//Inserting New Bowler In The Database And Refreshing The List
private void createBowler(String leagueId, String bowlerName) {
String bowlerAverage = "0";
//Inserting Bowler In The Database And Getting Newly Inserted Bowler Id
long id = db.insertBowler(leagueId, bowlerName, bowlerAverage);
//Get The Newly Inserted Bowler From The Database
Bowler n = db.getBowler(leagueId);
if (n != null) {
//Adding New Bowler To The Array List At Position 0
bowlersList.add( 0, n );
//Refreshing The List
mAdapter.notifyDatasetChanged(db.getAllBowlers(savedLeagueId));
//mAdapter.notifyDataSetChanged();
toggleEmptyBowlers();
}
}
//Updating Bowler In The Database And Updating The Item In The List By Its Position
private void updateBowler(String bowlerName, int position) {
Bowler n = bowlersList.get(position);
//Updating Bowler Text
n.setLeagueId(savedLeagueId);
n.setName(bowlerName);
//Updating The Bowler In The Database
db.updateBowler(n);
//Refreshing The List
bowlersList.set(position, n);
mAdapter.notifyItemChanged(position);
toggleEmptyBowlers();
}
//Deleting Bowler From SQLite Database And Removing The Bowler Item From The List By Its Position
public void deleteBowler(int position) {
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "Series will be deleted.", Snackbar.LENGTH_LONG)
.setActionTextColor(Color.YELLOW)
.setAction("OK", new View.OnClickListener() {
#Override
public void onClick(View v) {
//Deleting The Bowler From The Database
db.deleteBowler(bowlersList.get(position));
//Removing The Bowler From The List
bowlersList.remove(position);
mAdapter.notifyItemRemoved(position);
db.leagueAverageScore(savedLeagueId);
toggleEmptyBowlers();
}
});
snackbar.show();
}
//Opens Dialog With Edit/Delete Options
private void showActionsDialog(final int position) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
View view = View.inflate(this, R.layout.dialog_options_1, null);
final AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(new ContextThemeWrapper(BowlerActivity.this, R.style.AppTheme));
alertDialogBuilderUserInput.setView(view);
alertDialogBuilderUserInput.setCancelable(true);
final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
//Cancel
final ImageButton cancel_btn = (ImageButton) view.findViewById(R.id.cancel);
cancel_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
alertDialog.cancel();
}
});
//Edit
ImageButton edit_btn = (ImageButton) view.findViewById(R.id.edit);
edit_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showBowlerDialog(true, bowlersList.get(position), position);
alertDialog.dismiss();
}
});
ImageButton delete_btn = (ImageButton) view.findViewById(R.id.delete);
delete_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "Bowler will be deleted.", Snackbar.LENGTH_LONG)
.setAction("OK", new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteBowler(position);
}
});
snackbar.show();
alertDialog.dismiss();
}
});
Window window = alertDialog.getWindow();
window.setGravity(Gravity.TOP);
alertDialog.show();
}
//Show Alert Dialog With EditText Options to Enter/Edit A League
//When shouldUpdate = true, It Will Automatically Display Old Bowler Name And Change The Button Text To UPDATE
public void showBowlerDialog(final boolean shouldUpdate, final Bowler bowler, final int position) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
final View view = View.inflate(this, R.layout.dialog_bowler, null);
AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(new ContextThemeWrapper(BowlerActivity.this, R.style.AppTheme));
alertDialogBuilderUserInput.setView(view);
alertDialogBuilderUserInput.setCancelable(true);
leagueId.setText(savedLeagueId);
final EditText inputBowlerName = view.findViewById(R.id.etBowlerNameInput);
TextView dialogTitle = view.findViewById(R.id.dialog_title);
dialogTitle.setText(!shouldUpdate ? getString(R.string.lbl_new_bowler_title) : getString(R.string.lbl_edit_bowler_title));
if (shouldUpdate && bowler != null) {
leagueId.setText(bowler.getLeagueId());
inputBowlerName.setText(bowler.getName());
}
alertDialogBuilderUserInput
.setCancelable(false)
.setPositiveButton(shouldUpdate ? "update" : "save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
}
})
.setNegativeButton("cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
dialogBox.cancel();
}
});
ImageView bowlerName = (ImageView) view.findViewById (R.id.ivBowlerName);
bowlerName.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder bowlerName = new AlertDialog.Builder(BowlerActivity.this);
bowlerName.setMessage("Enter the name of the bowler to hold your new scores.");
bowlerName.setCancelable(true);
bowlerName.create();
bowlerName.show();
}
});
final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
alertDialog.show();
alertDialog.getButton( AlertDialog.BUTTON_POSITIVE).setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
//Show Toast Message When No Text Is Entered
if (TextUtils.isEmpty(inputBowlerName.getText().toString())) {
Snackbar.make( view, "Enter Bowler Name", Snackbar.LENGTH_LONG )
.setAction( "Action", null ).show();
return;
} else {
alertDialog.dismiss();
}
//Check If User Is Updating Bowler
if (shouldUpdate && bowler != null) {
//Updating Bowler By Its Id
updateBowler(inputBowlerName.getText().toString(), position);
} else {
//Creating New Bowler
createBowler(leagueId.getText().toString(), inputBowlerName.getText().toString());
}
}
});
}
//Toggling List And Empty Bowler View
private void toggleEmptyBowlers() {
//You Can Check bowlerList.size() > 0
if (db.getBowlersCount() > 0) {
noBowlersView.setVisibility( View.GONE);
} else {
noBowlersView.setVisibility( View.VISIBLE);
}
}
#Override
public void onRestart() {
super.onRestart();
//When BACK BUTTON is pressed, the activity on the stack is restarted
//Do what you want on the refresh procedure here
}
#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_main, 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) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
overridePendingTransition(0, 0);
return true;
}
return super.onOptionsItemSelected( item );
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
//Check If Request Code Is The Same As What Is Passed - Here It Is 1
if(requestCode==1)
{
String savedLeagueId=data.getStringExtra("seriesLeagueId");
String seriesBowlerId=data.getStringExtra("seriesBowlerId");
bowlersList.addAll(db.getAllBowlers(savedLeagueId));
}
}
#Override
public void onBackPressed() {
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
overridePendingTransition(0, 0);
}
}
This is the line that it is complaining about. This worked perfectly before I move the onClick() to the adapter.
savedLeagueId = String.valueOf(getIntent().getIntExtra("leagueId",2));
I am really hoping that someone can help me get this issue resolved. I have tried several different approaches from other stackoverflow posts and I am still not able to resolve it.
mAdapter.notifyItemRemoved(position);
Means that the adapter will shift and animate items up. However, the items will not be redrawn.
You can observe that by clicking on the last item of your list after deleting any item: you should see the same crash.
And by clicking on any item after the one you deleted (except the last one), the details view should show the next item instead of the one you clicked.
The issue is that position is no longer relevant, because the indices have changed. Instead use the value for leagueId that you already have in your binder. Simply remove the int leagueId that is shadowing the String leagueId and that should work as expected.
The problem is that the view was already bind and the position at this method:
holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int leagueId = leaguesList.get(position).getId(); // here position will still be 1 after deletion
//...
}
});
belongs to the old index. To fix it, use the same object you fot previously.
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int leagueId = league.getId(); //league object will be the same
//...
}
});
****Try This****
#Override
protected void onBindViewHolder(#NonNull final BoardsViewHolder holder, final int position, #NonNull final Board model) {
holder.setTitle(model.getBoardTitle());
holder.setDesc(model.getBoardDesc());
holder.setDate(model.getCreatedOn());
holder.mDeleteBoardButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
alert.setTitle("Delete Board");
alert.setMessage("This Board will be deleted forever");
alert.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final ProgressDialog loading = new ProgressDialog(mContext);
loading.setMessage("Deleting...");
loading.show();
getSnapshots().getSnapshot(position).getReference().delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
notifyDataSetChanged();
loading.dismiss();
}else {
loading.dismiss();
Toast.makeText(mContext,"Something went wrong please try again later",Toast.LENGTH_LONG).show();
}
}
});
}
});
alert.setNegativeButton("Keep", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
}
});
This is the problem of zero based elements. Your code is trying to access an non existing element index. Launch your app in debug mode and line by line see what is happening. Android studio has an excellent debugger built-in, so it is very easy to go step by step and see what is happening with your variables.
ViewToken.class:
spinnerGenre = (Spinner) findViewById(R.id.spinnerGenres);
spinnerGenre1 = (Spinner) findViewById(R.id.spinner);
docname = spinnerGenre1.getSelectedItem().toString();
session = spinnerGenre.getSelectedItem().toString();
next=(Button)findViewById(R.id.button4);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next=new Intent(ViewToken.this,Tokens.class);
next.putExtra("docname", docname.toString());
next.putExtra("session", session.toString());
startActivity(next);
}
});
Tokens.class
Intent i2 = getIntent();
final String docname = i2.getStringExtra("docname");
final String session = i2.getStringExtra("session");
The spinner value from ViewToken.class is not passed to Tokens.class
Change this in ViewToken.class
next.putExtra("docname", docname);
next.putExtra("session", session);
You can do the following in your Tokens.class
Bundle extras = getIntent().getExtras();
String docname = extras.getString("docname");
String session = extras.getString("session");
The calls to getSelectedItem() should be made in the onClick listener so that it gets the most up-to-date values selected.
So instead the onClick() method will be:
#Override
public void onClick(View v) {
docname = spinnerGenre1.getSelectedItem().toString();
session = spinnerGenre.getSelectedItem().toString();
Intent next=new Intent(ViewToken.this,Tokens.class);
next.putExtra("docname", docname);
next.putExtra("session", session);
startActivity(next);
}
It is likely that the calls to getSelectedItem() where being made before anything was selected and therefore the values being put() inside the intent where incorrect.
get the values from the spinners just before send them.
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
docname = spinnerGenre1.getSelectedItem().toString();
session = spinnerGenre.getSelectedItem().toString();
Intent next=new Intent(ViewToken.this,Tokens.class);
next.putExtra("docname", docname.toString());
next.putExtra("session", session.toString());
startActivity(next);
}
});
int positionOfSelectedDataFromSpinner;
iv.putExtra("position", positionOfSelectedDataFromSpinner);
Create a New Method
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
positionOfSelectedDataFromSpinner= i;
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
And In Second Activity
int positionToShowToSpinner = iv.getIntExtra("position",0);
spinner.setSelection(positionToShowToSpinner);