I am trying to create a simple grade tracker for android. The way I have it set up is that the user has a list of classes that are in their major. When they click on the title of the class, a new activity starts that has the name of the class, the catalog description, a space to place your grade, and a button to return to the list of classes.
What I would like to do is save the grade number that they input on the second page, and when the button is pressed, on the first page the grade is shown next to the course title.
I have edited to the code to reflect the comments given.
This is the code that works!
CoreClasses
TextView eng101, eng101scr;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.classcore);
eng101 = (TextView)findViewById(R.id.eng101);
eng101scr = (TextView)findViewById(R.id.eng101CoreScr);
eng101.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(ClassCore.this, Eng101.class);
i.putExtra("grades", "eng101" );
startActivityForResult(i, 1);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(data.getExtras().containsKey("e101FinalScore")){
eng101scr.setText(data.getStringExtra("e101FinalScore"));
}
Eng101
public class Eng101 extends Activity {
Button btnSubmit;
EditText userGrade;
String strGrade;
OutsideVariables outside = new OutsideVariables();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.eng101);
btnSubmit = (Button)findViewById(R.id.btnE101);
userGrade = (EditText)findViewById(R.id.eng101Scr);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
strGrade = userGrade.getText().toString();
Intent i = getIntent();
String msg = i.getStringExtra("grades");
if(msg.contentEquals("eng101")){
i.putExtra("e101FinalScore", strGrade);
setResult(RESULT_OK, i);
finish();
}
}
});
}
}
You can pass the values to the previous activity by,
Intent intent = new Intent(Eng101.this, ClassCore.class);
intent.putExtra("grade",grade);
startActivity(new Intent(Eng101.this, ClassCore.class));
and in ClassCore you can get the value grade by,
Bundle extras = getIntent().getExtras();
// get data via the key
if(extras!=null){
int value1 = intent.getIntExtra("grade", 0);
if (value1 != null) {
eng101scr.setText(value1);
}
}
Because you're using an instance, each new instance will have it's own storage and values. What you're looking to do is actually much simpler than this, and it's to do everything using static access.
However, the better way to do this would be to create some sort of class like your OutsideVariables and pass an instance into your new activity, that way you're able to access them in both. Take a look at this other post for some more information. How to pass the values from one activity to previous activity
Related
i am trying to pass values of filtered chips that a user has selected in order to retrieve only the required shops he want in that particular criteria.
now i created everything and the data i am getting after finishing from my FilterActivity is being passed into my HomeActivity. but this data is not being 'read' or 'accepted' inside my query since it doesn't produce the correct output. When i use a static value inside the query it would work. now i need it to be a changing value depending on what the use has selected.
This is inside my HomeActivity that opens the Filter Activity:
filterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(HomeActivity.this,FilterActivity.class);
startActivityForResult(intent,101);
}
});
this is my FilterActivity with a few examples:
private Chip rate2,rate3,rate4;
private ArrayList<String> selectedChipData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filter);
rate2 = findViewById(R.id.chip_Rate_2);
selectedChipData = new ArrayList<>();
CompoundButton.OnCheckedChangeListener checkedChangeListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(isChecked){
selectedChipData.add(compoundButton.getText().toString().trim());
}else{
selectedChipData.remove(compoundButton.getText().toString().trim());
}
}
};
rate2.setOnCheckedChangeListener(checkedChangeListener);
}
and this is the button the user clicks when he wants to apply one of the filter options:
filter_reset = findViewById(R.id.filter_reset);
filter_reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent resultIntent = new Intent();
resultIntent.putExtra("data",selectedChipData.toString().trim());
setResult(101,resultIntent);
finish();
}
});
now in my HomeActivity i created the onActivityResult:
String Data;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==101){
Data = data.getStringExtra("data");
Log.d("TAG", data.getStringExtra("data"));
Query q = firebaseFirestore.collection("Shops").whereEqualTo("location",Data);
}
}
Query q = firebaseFirestore.collection("Shops").whereEqualTo("location",Data);
// this is my query and how i am trying to pass the matched users selected chip to the location of the Shops table.
What am i missing or doing wrong inside my query and how to fix it? can someone advise?
Did by any chance you forget to tell intent to go back to Home Page
filter_reset = findViewById(R.id.filter_reset);
filter_reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent resultIntent = new Intent(FilterActivity.this, MainActivity.class);
// Changed the above Intent Paras
resultIntent.putExtra("data",selectedChipData.toString().trim());
setResult(101,resultIntent);
finish();
}
});
i found the problem, it wasn't matching with my database because the value is an array and has [] in the result. if i put the [] in my database it works fine.
The codes are messy at this point since I've been going back and forth so much. Every time user clicks the yes/no button I want the results of counts the button has been clicked to display in another activity. I also want to reset the number of clicks from the second activity as well. All that's needed in the first activity is the question and the yes/no button. Is this possible? Thanks in advance.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "SurveyActivity";
private static final String YES_INDEX = "yes votes";
private static final String NO_INDEX = "no votes";
Button mYesButton;
Button mNoButton;
Button mResetButton;
TextView mSurveyQuestion;
private int yesVoteCount = 0;
private int noVoteCount = 0;
private int resetVotes = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Use res ID to retrieve inflated objects and assign to variables
mYesButton = findViewById(R.id.yes_button);
mNoButton = findViewById(R.id.no_button);
mResetButton = findViewById(R.id.reset_button);
mSurveyQuestion = findViewById(R.id.survey_question);
mYesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addVote();
}
});
mNoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addVote();
}
});
// Resetting vote count
mResetButton.setOnClickListener(new View.OnClickListener() {
#Override
***Should this supposed to be in the second activity?
}
});
}
private void addVote() {
if (mYesButton.isPressed()) {
yesVoteCount++;
} else if (mNoButton.isPressed()) {
noVoteCount++;
}
}
In your main activity
btnShowResut.setOnClickListener(new View.OnClickListener() {
#Override
// Create intent for going to another activity
Intent intent = new Intent(this, AnotherActivity.class);
// Put counts datas to intent
intent.putExtra("yesCountKey", yesVoteCount);
intent.putExtra("noCountKey", noVoteCount);
// NEW : Go to another activity by calling it instead
// REQUEST_CODE is an integer variable
startActivityForResult(intent, REQUEST_CODE);
}
});
In Another activity, you can retrieve datas in onCreate method like this and send action to clear counts of your main activity.
...
onCreate(...){
...
// Retrieve datas from intent
int yesCount = getIntent().getIntExtra("yesCountKey", 0);
int noCount = getIntent().getIntExtra("noCountKey", 0);
mResetButton.setOnClickListener(new View.OnClickListener() {
#Override
// Send a boolean to main activity for clearing votes
Intent intent = new Intent();
intent.putExtra("resetVotes", true);
setResult(RESULT_OK, intent);
// Close second activity
finish();
}
});
}
Finally in the main activity override this method and clear votes
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == 2000 && resultCode == RESULT_OK){
boolean reset = data.getBooleanExtra("resetVotes", false);
if(reset){
yesVoteCount = 0;
noVoteCount = 0;
}
}
}
As the mentioned above, you can get the counts by using intent extras.
However if you want to reset the counts in in the second activity you might want to start the Activity B as startActivityForResult() see the Android documentation here.
Then when Activity B end you can reset the counts in the call back method onActivityResult().
If you don't want to do it like this the next best way might be to reset the counts onResume() of Activity A so that when you return to the activity you will start with fresh counts. See life cycle documentation here
So I'm developing currently my own private App which I want to use only for me and maybe some friends.
Well I'm german so my english is maybe not the best I hope you can forgive me.
Now my Problem is that I want to set in my Optionsmenu a Budget for the current month to keep track of. I'm doing that by using an EditText with a Button.
Now I want to save this String which is getting entered in my EditText to a String value and a Integer value because I want to show the Value in a TextView on my MainPage and use the Integer value to calculate my current budget I got and so on.
Now I'm showing you guys my code and I hope u can tell me whats wrong with it.
I'm trying to get my Value in the Options class which is related to my OptionsMenu and later Trying to get the Value out of my Options class into my Main class.
public class Options extends Activity {
Button GoBack, SetBudget;
private int Budget;
String BudgetString = "";
EditText BudgetEdit;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
GoBack = (Button) findViewById(R.id.button2);
GoBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent GoBackToMain = new Intent("com.lunarrepublic.STARTINGPOINT");
startActivity(GoBackToMain);
}
});
SetBudget = (Button) findViewById(R.id.button8);
SetBudget.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
BudgetEdit = (EditText) findViewById(R.id.editText1);
BudgetString = EditText.getText();
//In the Line above this is the error "Type mismatch. Cannot convert Editable to String
Budget = Integer.parseInt(BudgetString);
}
});
}
But if I try to set my "BudgetString" to Editable It won't work either.
The GoBack Button is unnecessary for my problem here so you don't have to read over it.
So I hope you guys understood what my problem is and can maybe help me getting it fixed
Thanks in advance
This is wrong
BudgetString = EditText.getText();
Use below one
BudgetString = BudgetEdit.getText().toString();
change this
SetBudget.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
BudgetEdit = (EditText) findViewById(R.id.editText1);
BudgetString = EditText.getText();
//In the Line above this is the error "Type mismatch. Cannot convert Editable to String
Budget = Integer.parseInt(BudgetString);
}
});
to
SetBudget.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
BudgetEdit = (EditText) Options.this.findViewById(R.id.editText1);
BudgetString = BudgetEdit.getText();
//In the Line above this is the error "Type mismatch. Cannot convert Editable to String
Budget = Integer.parseInt(BudgetString);
}
});
i'm developing a scan Barcode app on android , my application is simple and composed from an activity which contains a button and a textView which will receive the result of the scan.. The app works well but i want that i could realise serial scan in a raw. so after scanning a barcode i need that the capture Activity stay and the appli don't back to the button activity so i can scan the next Barcode. any solution please ?
this is my main java code :
public class MainActivity extends Activity {
private Button scan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scan= (Button)findViewById(R.id.btnScan);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
});
}
public boolean onTouchEvent(final MotionEvent event) {
IntentIntegrator integrator = new IntentIntegrator();
integrator.initiateScan(null);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = data.getStringExtra("SCAN_RESULT");
TextView tv = (TextView) findViewById(R.id.scanResult);
tv.setText(data.getStringExtra("SCAN_RESULT"));//this is the result
} else
if (resultCode == RESULT_CANCELED) {
// Handle cancel
} }
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
}
I had the same problem when I did my scanner activity, and the solution that I found was to make my mainActivity extends Zxing CaptureActivity, like this I overrided handleDecode and I avoided to switch between different activities (as you have to do to obtain your scanner result).
Anyhow, to restart the scanning process after a precedent scan I called the method
restartPreviewAfterDelay(0L)
(that is a method of CaptureActivity) in the onClick function of a button.
Take a look at that method, I think that it is what you need.
i finally found the solution i had just to add this code in the onActivityResult() declaration
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
So after the scan is finished the app is ready to scan again instead of going back to the home activity
I have a MainActivity which has a ListView, when I click the ListView it opens a new activity for that item.
I want to be able to change the information in that item, then when I click back it changes the ListView.
Here's some of the code I have:
MainActivity:
String[] people;
private ListView mListView;
public static ArrayAdapter<String> adapter;
In onCreate(){
people = new String[] {"", "", "", "", "", "", "", ""};
mListView = (ListView) findViewById(R.id.personListView);
adapter = (new ArrayAdapter<String>(this, R.layout.list_item, people);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Current item
String person = ((TextView) view).getText().toString();
// Launch new activity based on item
Intent intent = new Intent(getApplicationContext(), SinglePerson.class);
//
intent.putExtra("person", person);
//intent.putExtra("peopleList", people);
intent.putExtra("position", position);
startActivityForResult(intent, 1);
//
}
});
I have this in the class which I thought would get the information from the other activity back but nothing happens:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == 1) {
// Make sure the request was successful
if(resultCode == RESULT_OK){
int listPos = data.getIntExtra("listPosition", 1);
//edit listview value at position
people[listPos] = data.getStringExtra("edittextvalue");
adapter.notifyDataSetChanged();
}
}
}
In the other activity class:
public class SinglePerson extends Activity{
String[] people;
int position;
Intent intent;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_person_item_view);
EditText txtPerson = (EditText) findViewById(R.id.person_name);
intent = getIntent();
String person = intent.getStringExtra("person");
//people = intent.getStringArrayExtra("peopleList");
position = intent.getIntExtra("position", 0);
txtPerson.setText(person);
}
private TextWatcher peopleNumberListener = new TextWatcher(){
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
//people[position] = s.toString();
//BillSplit.adapter.notifyDataSetChanged();
intent.putExtra("edittextvalue",s.toString());
intent.putExtra("listPosition", position);
setResult(RESULT_OK, intent);
//finish();
}
};
As per my comment above, if you are pressing the back key then you're not properly finishing the Activity. What you want to do is when you're ready to end the Activity, either in a Button or some other action, then do the following (which it looks like you had already mostly figured out)
...
// you can create a new Intent for the result
Intent newIntent = new Intent();
newintent.putExtra("edittextvalue",s.toString());
newintent.putExtra("listPosition", position);
setResult(RESULT_OK, newintent);
finish();
...
EDIT: In response to those who are posting to override onBackPressed(), this will allow you to intercept the back key when you press it within your Activity and decide how you want to handle it. However, please note the implication of doing this: if this is for the general public, most users will expect the back key to take you some form of "back", but this is not the same as completion or progressing through the normal flow of your app (which you are looking to do by making a selection and then continue where you left off). So while this may accomplish the desired behavior, it's debatable whether this is the correct solution for you.
I would use Singleton if you have more than two activities. If its just two then probably using intent.put. Thanks,