Enusuring spinner value selected, or button not allowed to be selected - java

I am new to android studio and have created an app with a page that enables 2 spinners to be selected, a user enters a time and then an 'end time' is calculated. I am trying to add some validation to this page as when I click the 'VerifyButton' the app crashes as no fields have been selected. My intention is that when the user selects the 'VerifyButton' that an error message displays to ensure the spinner values have been filled in, meaning the app doesn't crash. I have tried a few methods within the onNothingSelected but it doesn't seem to work.. I wasn't sure if it needs to be in there or the VerifyButton? Thanks in advance!
Spinner Java
final ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(CreateLine.this,
R.layout.spinner_layout, getResources().getStringArray(R.array.LineTypes));
myAdapter.setDropDownViewResource(R.layout.spinner_layout);
spinner.setAdapter(myAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position2, long l) {
switch (position2) {
case 0:
quantity.setText("");
break;
case 1:
quantity.setVisibility(View.INVISIBLE);
timeadded = 10;
duration.setText(timeadded + " Hours");
spinner2.setVisibility(View.INVISIBLE);
break;
case 2:
quantity.setVisibility(View.INVISIBLE);
timeadded = 10;
duration.setText(timeadded + " Hours");
spinner2.setVisibility(View.INVISIBLE);
break;
case 3:
quantity.setVisibility(View.INVISIBLE);
timeadded = 10;
duration.setText(timeadded + " Hours");
spinner2.setVisibility(View.INVISIBLE);
break;
case 4:
quantity.setVisibility(View.VISIBLE);
duration.setText(timeadded + " Hours");
spinner2.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Select Package Type", Toast.LENGTH_SHORT).show();
break;
case 5:
quantity.setVisibility(View.VISIBLE);
duration.setText(timeadded + " Hours");
spinner2.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Select Package Type", Toast.LENGTH_SHORT).show();
break;
case 6:
quantity.setVisibility(View.VISIBLE);
duration.setText(timeadded + " Hours");
spinner2.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Select Package Type", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
ArrayAdapter<String> myAdapter2 = new ArrayAdapter<String>(CreateLine.this,
R.layout.spinner_layout, getResources().getStringArray(R.array.PackageTypes));
myAdapter2.setDropDownViewResource(R.layout.spinner_layout);
spinner2.setAdapter(myAdapter2);
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
switch (position) {
case 0:
quantity.setText("");
break;
case 1:
quantity.setText(PackageType20);
timeadded = 28;
duration.setText(timeadded + " Hours");
break;
case 2:
quantity.setText(PackageType30);
timeadded = 27;
duration.setText(timeadded + " Hours");
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
VerifyButton Java
VerifyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
spinnerSelection = String.valueOf(spinner.getSelectedItem());
spinnerSelection2 = String.valueOf(spinner2.getSelectedItem());
String q = quantity.getText().toString();
String d = duration.getText().toString();
DateTime datetime = new DateTime(yearNow, monthNow, dayNow, hourNow, minuteNow);
DateTimeFormatter fmt = DateTimeFormat.forPattern("EE dd MM yyyy" + "\n" + " h:mm a ");
String formattedtime = fmt.print(datetime);
CalculateButton.setText(formattedtime);
// Plus some hours, minutes, and seconds to the original DateTime.
DateTimeFormatter fmt2 = DateTimeFormat.forPattern("EE dd MM yyyy" + "\n" + " h:mm a ");
DateTime dateTime1 = datetime.plusHours(timeadded);
String endtimecalc = fmt2.print(dateTime1);
TextView endtime = findViewById(endtimetextView);
endtime.setVisibility(View.VISIBLE);
endtime.setText(endtimecalc);
if (spinnerSelection !=null) {
Toast.makeText(getApplicationContext(),"enter value",
Toast.LENGTH_LONG).show();
}
//INSERT DATA TO DATABASE
boolean isInserted = myDb.insertData(
spinnerSelection,
spinnerSelection2,
q,
d,
formattedtime,
endtimecalc);
if (isInserted == true)
Toast.makeText(CreateLine.this, "Data Inserted Successfully", Toast.LENGTH_LONG).show();
else
Toast.makeText(CreateLine.this, "This line is already Active!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), Dashboard.class);
startActivity(intent);
}
});

Replace all of your :
getApplicationContext()
with:
getContext()
and in following line instead of getApplicationContext():
Intent intent = new Intent(getApplicationContext(), Dashboard.class);
Use your class name as follows:
Intent intent = new Intent(YourClassName.this, Dashboard.class);
Class in which you are defining your verify button.
And in both of onNothingSelected methods set default value for spinner as:
ArrayList<String> list = getResources().getStringArray(R.array.LineTypes);
yourSpinner.setSelection(list[0]);
Also apply check instead of this:
if (spinnerSelection !=null) {
Toast.makeText(getApplicationContext(),"enter value",
Toast.LENGTH_LONG).show();
}
As:
if (spinnerSelection.getSelectedItem().toString().isEmpty() || spinnerSelection.getSelectedItem().toString() == "" )
{
Toast.makeText(getApplicationContext(),"enter value",
Toast.LENGTH_LONG).show();
}

After spinner.setAdapter(myAdapter) add;
spinner.setAdapter(myAdapter)
spinner.setSelection(-1);
then on verify button click:
if (spinner.getSelectedItemPosition() == -1 || spinner2.getSelectedItemPosition() == -1 ){
// showErrorMessage
}
else{
//do your work
}
Do the same for spinner2

Related

null value on variable passed from inside a onclick response

Is there any reason why method CreatePlan won't allow me access to variable recipe_name from the onRecipeClicked function which is retrieved from the recyclerview adapter. The Log shows that the value is retrieved from the recyclerview, but I can't seem to pass it to another method.
Any help is appreciated.
Update
Also is there a way of assigning the auto incremented id created from createPlanRecipe to the id variable in createPlan?
public class CreateMealPlan extends MainActivity {
DatePicker datepicker;
Button submit;
List<com.stu54259.plan2cook.Model.Category> listRecipe = new ArrayList<>();
Cursor c;
RecyclerView recipeList;
RecipeListAdapter adapterRecipe;
String recipe_name;
EditText editPlanName;
Integer id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_meal_plan);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent a = new Intent(CreateMealPlan.this,MainActivity.class);
startActivity(a);
break;
case R.id.recipes:
Intent b = new Intent(CreateMealPlan.this,RecipeSearch.class);
startActivity(b);
break;
/*case R.id.shoppingList:
Intent c = new Intent(CreateMealPlan.this, ShoppingList.class);
startActivity(c);
break;*/
case R.id.mealPlan:
Intent d = new Intent(CreateMealPlan.this, MenuPlan.class);
startActivity(d);
break;
/*case R.id.reminder:
Intent e = new Intent(CreateMealPlan.this, Reminder.class);
startActivity(e);
break*/
}
return false;
}
});
datepicker = findViewById(R.id.calendarView);
ListRecipes();
RecipeListAdapter.OnRecipeClickListener listener = new RecipeListAdapter.OnRecipeClickListener() {
public void onRecipeClicked(int position, String recipe_name) {
Log.d("Recipe selected", recipe_name);
}
};
adapterRecipe = new RecipeListAdapter(this, listRecipe, listener);
recipeList = findViewById(R.id.recipes);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
recipeList.setLayoutManager(mLayoutManager);
recipeList.setItemAnimator(new DefaultItemAnimator());
recipeList.setAdapter(adapterRecipe);
submit = (Button) findViewById(R.id.create);
// perform click event on submit button
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CreatePlan();
}
});
}
public void ListRecipes() {
listRecipe.clear();
SQLiteDatabase db = (new DatabaseManager(this).getWritableDatabase());
String selectQuery = " SELECT recipe_name, image, image2, category" + " FROM " + DatabaseManager.TABLE_RECIPE + " GROUP BY recipe_name";
c = db.rawQuery(selectQuery, null);
Log.d("Query", selectQuery);
if (c.moveToFirst()) {
do {
com.stu54259.plan2cook.Model.Category category = new com.stu54259.plan2cook.Model.Category();
category.setRecipe_name(c.getString(c.getColumnIndex("recipe_name")));
category.setImage(c.getInt(c.getColumnIndex("image")));
category.setImage2(c.getString(c.getColumnIndex("image2")));
category.setCategory_name(c.getString(c.getColumnIndex("category")));
listRecipe.add(category);
} while (c.moveToNext());
c.close();
}
}
public void CreatePlan(){
editPlanName = findViewById(R.id.editPlanName);
String plan_name = editPlanName.getText().toString();
DatabaseManager db;
int day = datepicker.getDayOfMonth();
int month = datepicker.getMonth();
int year = datepicker.getYear();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Integer d_name = day;
Log.d("Date", String.valueOf(d_name));
String dayOfTheWeek = sdf.format(d_name);
String date = day + "/" + month + "/" +year;
db = new DatabaseManager(getApplicationContext());
db.createPlanRecipe(d_name, dayOfTheWeek, recipe_name);
db.createPlan(plan_name, id);
}
}

onclicklistener not working while using this code

the onclicklistener is not at all working while clicking
public void adddata()
{
subbtn.setOnClickListener(new View.OnClickListener()
{public void onClick(View v) {
Date d = new Date();
CharSequence s = DateFormat.format("MMMM d, yyyy ", d.getTime());
int total = Integer.parseInt(String.valueOf(foodtext.getText())) + Integer.parseInt(petroltext.getText().toString()) + Integer.parseInt(grocetext.getText().toString()) +
Integer.parseInt(sundrytext.getText().toString()) + Integer.parseInt(educatext.getText().toString()) + Integer.parseInt(loantext.getText().toString());
System.out.println(total);
boolean inserted = dbex.insertdata(Integer.parseInt(s.toString()), Integer.parseInt(foodtext.getText().toString()), Integer.parseInt(petroltext.getText().toString()), Integer.parseInt(grocetext.getText().toString()),
Integer.parseInt(sundrytext.getText().toString()), Integer.parseInt(educatext.getText().toString()), Integer.parseInt(loantext.getText().toString()), total);
if (inserted)
Toast.makeText(todayex.this, "datainserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(todayex.this, "datanotinserted", Toast.LENGTH_LONG).show();
}});
startActivity(intent);
}
}
while clicking that button it needs to open new activity as well should store my data into database

How I stop multi booking on same time?

I getting booking details from firebase firestore and set into Recyclerview by bean(DTO) class there i have time and date value in integer I wanna stop multi booking in same time or near 30 mints anyone tell me how can I stop it..??
Main Recyclerview Fragement There I getting value by firestore
RecyclerView listView=(RecyclerView)view.findViewById(R.id.listview);
lbean = new ArrayList<>();
sheduleAdapter= new SheduleAdapter(getActivity(),lbean);
listView.setHasFixedSize(true);
listView.setLayoutManager(new LinearLayoutManager(getActivity()));
listView.setAdapter(sheduleAdapter);
db.collection("users").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.d(TAG, "Error:" + e.getMessage());
}
for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {
switch (doc.getType()) {
case ADDED:
bean = doc.getDocument().toObject(bean.class);
lbean.add(bean);
sheduleAdapter.notifyDataSetChanged();
break;
case MODIFIED:
bean = doc.getDocument().toObject(bean.class);
lbean.add(bean);
sheduleAdapter.notifyDataSetChanged();
break;
case REMOVED:
lbean.remove(bean);
sheduleAdapter.notifyDataSetChanged();
break;
}
}
}
});
Recyclerview Adapter there i set value from bean class
holder.mint.setText(String.valueOf(bean.get(position).getMint()));
holder.hour.setText(String.valueOf(bean.get(position).getHour()));
holder.day.setText(String.valueOf(bean.get(position).getDay()));
holder.month.setText(String.valueOf(bean.get(position).getMonth()));
holder.year.setText(String.valueOf(bean.get(position).getYear()));
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar c=Calendar.getInstance();
iHour = c.get(Calendar.HOUR_OF_DAY);
iMin = c.get(Calendar.MINUTE );
iYear = c.get(Calendar.YEAR);
iMonth = c.get(Calendar.MONTH);
iDay = c.get(Calendar.DAY_OF_MONTH);
iMin=bean.get(position).getMint();
iHour=bean.get(position).getHour();
iDay=bean.get(position).getDay();
iMonth=bean.get(position).getMonth();
iYear=bean.get(position).getYear();
c.set(iYear,iMonth,iDay,iHour,iMin);
String mm = String.valueOf(iMin);
String h = String.valueOf(iHour);
String d = String.valueOf(iDay);
String m = String.valueOf(iMonth);
String y = String.valueOf(iYear);
Toast.makeText(context, mm + "==" + h + "==" + d + "==" + m + "==" + y, Toast.LENGTH_SHORT).show();
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference ref = db.collection("users").document();
final String myId = ref.getId();
Toast.makeText(context, myId, Toast.LENGTH_SHORT).show();
}
});
}

Why the name in listView keep changing?

I have a listView in Activity A as shown below. All the values and name were actually returned from Activity C to B then only A.
When the first list is clicked, it should display text Project and value 3 on editText B. But it displays Medical which was actually getting from the last list.
After I change the value from 3 to 43 and return to A, the name changed. What should I do so that the name will remain the same ?
Activity A
ArrayAdapter<String> adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
int mClickedPosition;
adapter=new ArrayAdapter<String (getActivity(),R.layout.claims,R.id.textView1,m_listItems);
listV = (ListView) claims.findViewById(R.id.listView1);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() { // if list clicked
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
mClickedPosition = position;
if (name.equals("Project")) {
String temp[] = m_listItems.get(position).split("\\s\\s+");
result = temp[temp.length - 1].trim();
result = result.replace("RM","");
Intent intent = new Intent(Claims1.this.getActivity(), Project1.class);
intent.putExtra("bitmap", true); // image
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 0);
Log.e("RESULT", "Result= " + result);
}
else if(name.equals("Medical"))
{
String temp[] = m_listItems.get(position).split("\\s\\s+");
result = temp[temp.length - 1].trim();
result = result.replace("RM","");
Intent intent = new Intent(Claims1.this.getActivity(), Medical.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 1);
}
}
});
return claims;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0: // for Project
result = data.getStringExtra("text"); //get from B
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:" + result);
Text = " " + name + " " + "RM" + result + "";
if (mClickedPosition == -1) { // if is icon button clicked
m_listItems.add(Text);
} else {
m_listItems.set(mClickedPosition, Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
case 1: // for Medical
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:" + result);
Text = " " + name + " " + "RM" + result + "";
// m_listItems.clear();
if (mClickedPosition==-1)
{
m_listItems.add(Text);
}
else
{
m_listItems.set(mClickedPosition, Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
Activity B (Project1)
if(getIntent().getExtras()!=null) { //if has value pass from A
final String Amount = getIntent().getExtras().getString("result");
final String description1 = getIntent().getExtras().getString("description");
txt1.setText(description1);
txt.setText(Amount);
}
b.setOnClickListener(new View.OnClickListener() { // return to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
returnIntent.putExtra("c", c); // receive from Activity C
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
viewImage.setImageBitmap(Global.img); // receive from C
}
Noted that the result in Activity A represents value 3,5 while name represents project and Medical. How can I fix this ? Please help.
From what I understood, your variable name in Activity A contains previously resulted value (from Activity B) and not from row you have clicked on listview i.e. "Medical" value you previously got from Activity B which held by variable name and on your listview click event you have checks the if name is "Medical" or "Project" (and in this case it is "Medical" and hence Medical activity is started).
One solution is to get the value("Project/Medical") from listview.
Try this code.
Activity A
mClickedPosition = position;
String temp[] = m_listItems.get(position).split("\\s\\s+");
result = temp[temp.length - 1].trim();
result = result.replace("RM","");
name = temp[1].trim();
if (name.equals("Project")) {
Intent intent = new Intent(Claims1.this.getActivity(), Project1.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 0);
Log.e("RESULT", "Result= " + result);
}
else if(name.equals("Medical"))
{
Intent intent = new Intent(Claims1.this.getActivity(), Medical.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 1);
}

What does requestCode and resultCode in onActivityResult refer to?

Good day guys. I'm new to android and now using startActivityForResult in my program. In my app, I have two button and two textView. The two button used to open the dialog. How can I check which button was pressed onActivityResult so that the TextView can be setText accordingly to the button?
int a1 = 1;
int a2 = 2;
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialogRadio(a1);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialogRadio(a2);
}
});
public void AlertDialogRadio(final int k) { //parameter k is never used
final CharSequence[] ClaimsModel = {"Project", "Petrol", "Car Maintenance"
, "Medical", "Other"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select a Claims");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Project1.class);
startActivityForResult(intent, 0);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Petrol.class);
startActivityForResult(intent, 1);
} else if (item == 2) {
Intent intent = new Intent(getActivity().getApplicationContext(), CarMainten.class);
startActivityForResult(intent, 2);
} else if (item == 3) {
Intent intent = new Intent(getActivity().getApplicationContext(), Medical.class);
startActivityForResult(intent, 3);
} else if (item == 4) {
Intent intent = new Intent(getActivity().getApplicationContext(), Other.class);
startActivityForResult(intent, 4);
}
dialog.dismiss();
}
});
AlertDialog alert = alt_bld.create();
alert.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 1) { // if button1 was clicked
switch (requestCode) {
case 0:
String result = data.getStringExtra("text");
String b = data.getStringExtra("a");
c.setText(" " + b + "------" + "RM " + result);
Toast.makeText(getActivity(), "Not completed ", Toast.LENGTH_LONG).show();
break;
case 1:
String result1 = data.getStringExtra("text");
String b1 = data.getStringExtra("a");
c.setText(" " + b1 + "------" + "RM " + result1);
break;
case 2:
String result2 = data.getStringExtra("text");
String b2 = data.getStringExtra("a");
c.setText(" " + b2 + "------" + "RM " + result2);
break;
case 3:
String result3 = data.getStringExtra("text");
String b3 = data.getStringExtra("a");
c.setText(" " + b3 + "------" + "RM " + result3);
break;
case 4:
String result4 = data.getStringExtra("text");
String b4 = data.getStringExtra("a");
c.setText(" " + b4 + "------" + "RM " + result4);
break;
}
}
else if (resultCode == 2) { // if button2 was clicked
switch (requestCode) {
case 0:
String result = data.getStringExtra("text");
String b = data.getStringExtra("a");
d.setText(" " + b + "------" + "RM " + result);
break;
case 1:
String result1 = data.getStringExtra("text");
String b1 = data.getStringExtra("a");
d.setText(" " + b1 + "------" + "RM " + result1);
break;
case 2:
String result2 = data.getStringExtra("text");
String b2 = data.getStringExtra("a");
d.setText(" " + b2 + "------" + "RM " + result2);
break;
case 3:
String result3 = data.getStringExtra("text");
String b3 = data.getStringExtra("a");
d.setText(" " + b3 + "------" + "RM " + result3);
break;
case 4:
String result4 = data.getStringExtra("text");
String b4 = data.getStringExtra("a");
d.setText(" " + b4 + "------" + "RM " + result4);
break;
}
}
}
So my program should work like this:
If button1 was clicked....c.setText();
If button2 was clicked....d.setText();
But the program now is nothing display on the TextView. Did the error came from if (resultCode == 1) and else if (resultCode == 2) ?? Thanks a lot
Assume the use select Project1.class
Project1.class
public class Project1 extends AppCompatActivity {
private static String text;
private static String a;
private static EditText txt;
private int g;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
txt= (EditText)findViewById(R.id.editText36);
Button b=(Button)findViewById(R.id.button17);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a="Project";
text = txt.getText().toString();
returnIntent.putExtra("text", text);
returnIntent.putExtra("a",a);
// returnIntent.putExtra("k",getIntent().getExtras().getString("k"));
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
}
request_code is the calling function identity, from where it is requested, result_code is the called function identifier, also it specifies status of the called message as Intent.ACTIVITY_OK and so on.
You should avoid using the literal code here.
if (resultCode == 1)
much better to use the named constant --
if (resultCode == RESULT_OK) {
RESULT_OK is -1, so that might be your issue.
Once I set all my request codes the same. Didn't work.
Seems your request codes are different, I'm used to seeing them like this:
private static final int REQUEST_CODE_THIS = 0;
private static final int REQUEST_CODE_THAT = 1;
private static final int REQUEST_CODE_THE_OTHER = 1003;
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Project1.class);
startActivityForResult(intent, REQUEST_CODE_THIS);
Check if changing the onActivityResult() like this might help.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_THIS) { // if button1 was clicked
switch (resultCode == RESULT_OK) {
case 0:
...
}

Categories