I'm trying to make an APK that saves passwords with the site using two different ArrayLists. This way, I can get the right indexnumber of the site and get the password based on this indexnumber. In the beginning of MainActivity, I add two random Strings to the ArrayLists, so that I don't have to work with empty ArrayLists, but this is utterly useless I think.
The problem is I can only view the last site-password I have put in. Previous combinations are "lost."
code:
MainActivity.java
package com.example.prive.passwordsafe;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public ArrayList<String> passwordList = new ArrayList<>();
public ArrayList<String> siteList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
passwordList.add("ejifjejfijeifjeijfiejifjeijfiejfijefie");
siteList.add("iejfijeifjiejfiejidvjijijeijivjiejvijeivjejv");
Button addButton = (Button) findViewById(R.id.addButton);
Button showButton = (Button) findViewById(R.id.showButton);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
firstIntent();
}
});
showButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
secondIntent();
}
});
}
#Override
public void onResume(){
super.onResume();
add();
}
private void firstIntent() {
Intent intent = new Intent(MainActivity.this, addActivity.class);
intent.putStringArrayListExtra("passwordList", passwordList);
intent.putStringArrayListExtra("siteList", siteList);
startActivity(intent);
}
private void secondIntent() {
Intent intent = new Intent(MainActivity.this, showActivity.class);
intent.putStringArrayListExtra("passwordList", passwordList);
intent.putStringArrayListExtra("siteList", siteList);
startActivity(intent);
}
public void add(){
Bundle pickupData = getIntent().getExtras();
if(pickupData == null){
return;
}
String receivedPassword = pickupData.getString("Password");
String receivedSite;
receivedSite = pickupData.getString("Site");
passwordList.add(receivedPassword);
siteList.add(receivedSite);
}
}
addActivity.java
package com.example.prive.passwordsafe;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class addActivity extends AppCompatActivity {
public EditText siteInsert, passwordInsert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toevoeg);
siteInsert = (EditText) findViewById(R.id.siteInsert);
passwordInsert = (EditText) findViewById(R.id.passwordInsert);
siteInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast msg = Toast.makeText(getBaseContext(), "site", Toast.LENGTH_LONG);
msg.show();
}
});
passwordInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast msg = Toast.makeText(getBaseContext(), "password", Toast.LENGTH_LONG);
msg.show();
}
});
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String password = passwordInsert.getText().toString();
String site = siteInsert.getText().toString();
Intent intent = new Intent(addActivity.this, MainActivity.class);
intent.putExtra("Password", password);
intent.putExtra("Site", site);
startActivity(intent);
}
});
}
}
showActivity.java
package com.example.prive.passwordsafe;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class showActivity extends AppCompatActivity {
public EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toon);
Button showButton = (Button) findViewById(R.id.showButton);
Button backButton = (Button) findViewById(R.id.backButton);
editText = (EditText) findViewById(R.id.editText);
final TextView textView = (TextView) findViewById(R.id.textView);
Bundle pickupData = getIntent().getExtras();
final ArrayList<String> passwordList = pickupData.getStringArrayList("passwordList");
final ArrayList<String> siteList = pickupData.getStringArrayList("siteList");
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast msg = Toast.makeText(getBaseContext(), "site", Toast.LENGTH_LONG);
msg.show();
}
});
if (passwordenList != null && siteList != null) {
showButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int numberOfPasswords = passwordenList.size();
for (int i = 0; i <= numberOfPasswords; i++) {
String password;
String temporary = editText.getText().toString();
if (temporary.equals(siteList.get(i))) {
password = passwordList.get(i);
textView.setText(password);
}else{
password = "wrong input";
textView.setText(password);
}
}
}
});
}else{
return;
}
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
When you exit an Activity, all the data on it is lost. You have to persist your ArrayList in SQLite or use SharedPreferences instead.
SharedPreferences: https://developer.android.com/reference/android/content/SharedPreferences.html
SQLite: https://developer.android.com/training/basics/data-storage/databases.html
Related
In my code, I have a class for a recipe and then another class for each step. The recipe class holds an arraylist of the steps in that recipe.
I have 3 processes being called one after the other:
MainActivity calls AddEditRecipe using startActivityResult
within AddEditRecipe I have another startActivityResult which calls AddStep
within AddStep I am adding a new instance of step to the list in the recipe.
It successfully adds the object to the list before finish() is called, but when I check the size of the list when I have gone to the 2nd activity it has reverted back to 0, even though I've managed to create buttons with the data I collected from the AddStep functions.
Basically I don't know what to do make it so it everything correctly persists.
Also a heads up, I am still fairly new too java so there's probably lots of other things wrong, any random advice is greatly appreciated.
MainActivity
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button newRecipe;
Button editRecipe;
Button deleteRecipe;
LinearLayout recipeLayout;
List<NewRecipe> listOfRecipes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listOfRecipes = new ArrayList<>();
recipeLayout = (LinearLayout) findViewById(R.id.RecipeListLayout);
newRecipe = (Button) findViewById(R.id.NewRecipeButton);
newRecipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, AddRecipePopUp.class);
startActivityForResult(i,998);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode==999 && resultCode == RESULT_OK){
NewRecipe rec = (NewRecipe)data.getParcelableExtra("curr_recipe");
Log.d("Number of Steps",Integer.toString(rec.listOfSteps.size()));
UpdateScreen(rec);
}
if(requestCode== 998 && resultCode == RESULT_OK){
NewRecipe recipe =(NewRecipe)data.getParcelableExtra("curr_recipe");
listOfRecipes.add(recipe);
Intent i = new Intent(MainActivity.this,AddEditRecipe.class);
i.putExtra("curr_recipe", recipe);
startActivityForResult(i,999);
}
}
void UpdateScreen(final NewRecipe recipe){
Button button = new Button(this);
button.setText(recipe.name);
button.setHeight(120);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NewRecipe recipe1 = recipe;
Button thisBut = (Button)view;
String butName = thisBut.getText().toString().toLowerCase();
for(int j = 0;j<listOfRecipes.size();j++){
String curr = listOfRecipes.get(j).name.toString().toLowerCase();
Log.d("Button ",thisBut.getText().toString());
Log.d("Current List ",listOfRecipes.get(j).name.toString().toLowerCase());
Log.d("Check bool statement", Boolean.toString(butName ==curr));
}
//recipe1 = listOfRecipes.get(0);
Intent i = new Intent(MainActivity.this, AddEditRecipe.class);
i.putExtra("curr_recipe",recipe1);
startActivityForResult(i,997);
}
});
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
recipeLayout.addView(button,lp);
}
}
AddEditRecipe
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class AddEditRecipe extends Activity {
Button home;
Button add;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_edit_recipe);
Intent i = getIntent();
final NewRecipe this_recipe = i.getParcelableExtra("curr_recipe");
Log.d("Number of Steps",Integer.toString(this_recipe.listOfSteps.size()));
LinearLayout recipeLayout = (LinearLayout) findViewById(R.id.RecipeListLayout);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
for(int j = 0; j<this_recipe.listOfSteps.size();j++){
Button button = new Button(this);
button.setText(this_recipe.listOfSteps.get(j).processName);
button.setHeight(120);
recipeLayout.addView(button,lp);
}
home = (Button) findViewById(R.id.HomeButton);
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(AddEditRecipe.this, MainActivity.class);
i.putExtra("curr_recipe", this_recipe);
setResult(RESULT_OK,i);
Log.d("Number of Steps",Integer.toString(this_recipe.listOfSteps.size()));
finish();
}
});
add = (Button) findViewById(R.id.AddStepButton);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(AddEditRecipe.this, AddStep.class);
i.putExtra("curr_recipe", this_recipe);
startActivityForResult(i,999);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode==999 && resultCode == RESULT_OK){
NewRecipe curr_rec = (NewRecipe)data.getParcelableExtra("curr_recipe");
Button button = new Button(this);
button.setText(curr_rec.listOfSteps.get(curr_rec.listOfSteps.size()-1).processName + " " + curr_rec.listOfSteps.get(curr_rec.listOfSteps.size()-1).seconds );
button.setHeight(120);
LinearLayout lay = (LinearLayout) findViewById(R.id.RecipeListLayout) ;
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lay.addView(button,lp);
}
}
}
AddStep
import android.app.Activity;
import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AddStep extends Activity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_step);
Intent i = getIntent();
final NewRecipe this_recipe = (NewRecipe) i.getParcelableExtra("curr_recipe");
Button finish = (Button) findViewById(R.id.AddStepButton);
finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText name = (EditText) findViewById(R.id.nameEditText);
EditText hours = (EditText) findViewById(R.id.HoursEditText);
EditText minutes = (EditText) findViewById(R.id.MinutesEditText);
EditText seconds = (EditText) findViewById(R.id.SecondsEditText);
this_recipe.AddStep((ConvertToSeconds(Integer.parseInt(hours.getText().toString()),Integer.parseInt(minutes.getText().toString()),Integer.parseInt(seconds.getText().toString()))),name.getText().toString());
Intent j = new Intent(AddStep.this, AddEditRecipe.class);
j.putExtra("curr_recipe", this_recipe);
Log.d("Number of Steps",Integer.toString(this_recipe.listOfSteps.size()));
setResult(RESULT_OK,j);
finish();
}
});
}
int ConvertToSeconds(int h, int m, int s){
int ans = 0;
for(int i = 0; i<h;i++){
ans+=3600;
}
for(int i = 0; i<m;i++){
ans+=60;
}
for(int i = 0; i<s;i++){
ans++;
}
return ans;
}
}
I have a problem in my code. I want to add items to a listview from another acivity onclickButton, but it only adds one item. And if I reapeat it, it only replaces the last added item. I can't figure out whats the problem some help please.
my code :
MainActivity:
package com.example.nasreddine.mtodubled; // project package
import android.app.AlertDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity; //imports statements
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import android.content.DialogInterface;
public class MainActivity extends AppCompatActivity {
AlertDialog.Builder alert;
public ArrayList<City> listItems;
ArrayAdapter adapter;
ListView cityListView;
#Override
protected void onCreate(Bundle savedInstanceState) { //onCreate State
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listItems=new ArrayList<>();
adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,listItems);
//Displaying Data on ListView
cityListView=(ListView)findViewById(R.id.cityListView);
cityListView.setAdapter(adapter);
registerForContextMenu(cityListView);
listItems.add(new City("a","b","","","","",""));
listItems.add(new City("v","c","","","","",""));
updateListView();
cityListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
cityListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Delete Item from list");
alert.setMessage("Are you sure you want to delete?");
alert.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listItems.remove(position);
adapter.notifyDataSetChanged();
}
});
alert.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.show();
return true;
}
});
}
public void updateListView() {
Bundle bundle = getIntent().getExtras();
Intent intent=getIntent();
if (bundle != null) {
City a=new City(intent.getStringExtra("city"),intent.getStringExtra("country"),"/","/","/","/","/");
//listItems.add(a);
adapter.add(a);
adapter.notifyDataSetChanged();
}
}
public boolean onOptionsItemSelected(MenuItem item){
if (item.getItemId()==R.id.action_add){
Intent intent=new Intent(MainActivity.this,AddCity.class);
startActivity(intent);
return (true);
}
return (super.onOptionsItemSelected(item));
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main,menu);
return super.onCreateOptionsMenu(menu);
}
}
AddCity.java
package com.example.nasreddine.mtodubled;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AddCity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_city);
Button addButton=(Button)findViewById(R.id.addButton);
final TextView cityAddText=(TextView)findViewById(R.id.cityAddText);
final TextView countryAddText=(TextView)findViewById(R.id.countryAddText);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String city= cityAddText.getText().toString();
String country=countryAddText.getText().toString();
Intent intent =new Intent(AddCity.this,MainActivity.class);
intent.putExtra("city",city);
intent.putExtra("country",country);
startActivity(intent);
}
});
}
}
In your MainActivity.class start the AddCity.class using startActivityForResult().
public boolean onOptionsItemSelected(MenuItem item){
if (item.getItemId()==R.id.action_add){
Intent intent=new Intent(MainActivity.this,AddCity.class);
startActivityForResult(intent, requestCode); //ex: requestCode = 1
return (true);
}
return (super.onOptionsItemSelected(item));
}
After that in AddCity change add button click listener code with below:
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String city= cityAddText.getText().toString();
String country=countryAddText.getText().toString();
Intent intent =new Intent();
intent.putExtra("city",city);
intent.putExtra("country",country);
setResult(RESULT_OK, intent);
finish();
}
});
After that in MainActivity's onActivityResult() get data and add it to list. Also remove updatListView() method from MainActivity.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
getActivity().invalidateOptionsMenu();
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
City a=new City(data.getStringExtra("city"),data.getStringExtra("country"),"/","/","/","/","/");
listItems.add(a);
adapter.add(a);
adapter.notifyDataSetChanged();
}
}
}
}
You are restarting the MainActivity from AddCity Activity.
Rather than doing this, you need to start AddCity Activity, using method startActivityForResult().
And in AddCity Activity, rather than starting new MainActivity, you need to use setResult() method to send data to previous activity.
Also you need to override the onActivityResult method in MainActivity Class to owner the response from AddCity Activity.
Cheers!!!
Here is the code:
Class Main Activity,
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
{
AlertDialog.Builder alert;
public List<City> listItems;
ArrayAdapter<City> adapter;
ListView cityListView;
#Override
protected void onCreate(Bundle savedInstanceState)
{ //onCreate State
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listItems = new ArrayList<>();
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItems);
//Displaying Data on ListView
Button addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startActivityForResult(new Intent(MainActivity.this, AddCity.class), 1);
}
});
cityListView = (ListView) findViewById(R.id.cityListView);
cityListView.setAdapter(adapter);
registerForContextMenu(cityListView);
listItems.add(new City("a", "b"));
listItems.add(new City("v", "c"));
updateListView();
}
public void updateListView()
{
Bundle bundle = getIntent().getExtras();
Intent intent = getIntent();
if(bundle != null)
{
City a = new City(intent.getStringExtra("city"), intent.getStringExtra("country"));
//listItems.add(a);
adapter.add(a);
adapter.notifyDataSetChanged();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
if(requestCode == 1 && resultCode == RESULT_OK)
{
City a = new City(intent.getStringExtra("city"), intent.getStringExtra("country"));
//listItems.add(a);
adapter.add(a);
adapter.notifyDataSetChanged();
}
}
}
Class Add City,
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AddCity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_city);
Button addButton = (Button) findViewById(R.id.addButton);
final TextView cityAddText = (TextView) findViewById(R.id.cityAddText);
final TextView countryAddText = (TextView) findViewById(R.id.countryAddText);
addButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String city = cityAddText.getText().toString();
String country = countryAddText.getText().toString();
Intent intent = new Intent();
intent.putExtra("city", city);
intent.putExtra("country", country);
setResult(RESULT_OK, intent);
}
});
}
}
Hopefully, this will help you.
Cheers!!!
i was making an android app and i need to use one integer value in 2 activities. I tried using this code but it didn't work.
//Integer Sender
Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("MyIntNameGoesHere", intValue);
startActivity(myIntent);
//Integer receiver
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
It says Cannot resolve symbol intValue and Cannot resolve symbol A and the same for B.
Here's the whole code.
MainActivity:
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int balance;
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//Click counter
final TextView text = (TextView) findViewById(R.id.balance_text);
assert text != null;
// to retreuve the values from the shared preference
preferences = PreferenceManager.getDefaultSharedPreferences(this);
balance = preferences.getInt("balance", 0);
text.setText(balance + " $");
final ImageButton button = (ImageButton) findViewById(R.id.click_button);
assert button != null;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
balance++;
text.setText("" + balance + " $");
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("balance", balance);
editor.apply();
}
});
final Button UpgradesButton = (Button) findViewById(R.id.upgrades_button);
assert UpgradesButton != null;
UpgradesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, UpgradesActivity.class));
}
});
//Balance Integer Sender
}
}
UpgradesActivity:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class UpgradesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upgrades);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
final Button e2u_button = (Button) findViewById(R.id.e2u_button);
assert e2u_button != null;
e2u_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
final Button back_button = (Button) findViewById(R.id.back_button);
assert back_button != null;
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(UpgradesActivity.this, MainActivity.class));
}
});
//TODO: Pass balance integer from MainActivity to here.
}
}
Error code:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class UpgradesActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upgrades);
//Receive balance from MainActivity
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("key_int", 0);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
final Button e2u_button = (Button) findViewById(R.id.e2u_button);
assert e2u_button != null;
e2u_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(balance >= 300){ //ERROR ON THIS LINE
}
}
});
final Button back_button = (Button) findViewById(R.id.back_button);
assert back_button != null;
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(UpgradesActivity.this, MainActivity.class));
}
});
//TODO: Pass balance integer from MainActivity to here.
}
}
ALL ABOVE IS ANSWERED! ---------------------------------------------------------
Now i have problems with this part of the code:
#Override
public void onClick(View v) {
if(balance >= 300){
balance -= 300;
}
if(balance < 300){
final TextView text = (TextView) findViewById(R.id.not_enough_money_text);
assert text != null;
text.setText("You do not have enough money.");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
text.setText("");
}
}, 2000);
}
}
When i click the button it says i do not have enough money but i have over 300. Please help me.
I found out what the problem was but I'm not sure how to fix it. I need to send balance back to MainActivity. Can anyone help with that?
Send the data like this -
UpgradesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, UpgradesActivity.class);
intent.putExtra("key_int", balance);
startActivity(intent);
}
});
And fetch it in onCreate() of UpgradesActivity -
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("key_int", 0);
You're using different key when sending and receiving the Int.
Change this line:
int intValue = mIntent.getIntExtra("intVariableName", 0);
To this:
int intValue = mIntent.getIntExtra("MyIntNameGoesHere", 0);
I need to take the values of a and b from the user via editText and pass it to the next activity.This is the first activity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.content.Intent;
import android.widget.EditText;
public class activitysecond extends AppCompatActivity {
private String[] arraySpinner;
private String[] arraySpinner2;
int a=0,b=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
final EditText editText1=(EditText) findViewById(R.id.editText1);
final EditText editText2=(EditText) findViewById(R.id.editText2);
final Bundle bundle = new Bundle();
Button EnterButton=(Button) findViewById(R.id.Enterbutton);
this.arraySpinner = new String[]{
"None", "Lightly Active", "Moderately Active", "Very Active"
};
Spinner s = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<>
(this,
android.R.layout.simple_spinner_dropdown_item, arraySpinner
);
s.setAdapter(adapter);
this.arraySpinner2 = new String[]{
"Male", "Female"
};
Spinner s1 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<String> adapter1 = new ArrayAdapter<>
(this,
android.R.layout.simple_spinner_dropdown_item, arraySpinner2
);
s1.setAdapter(adapter1);
editText1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a = Integer.valueOf(editText1.getText().toString());
bundle.putInt("one",a);
}
});
editText2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
b = Integer.valueOf(editText2.getText().toString());
bundle.putInt("two",b);
}
});
EnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent z = new Intent(activitysecond.this, activitythird.class);
startActivity(z);
z.putExtras(bundle);
}
});
}
}
The next activity to which i want to pass the values is
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class activitythird extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thirdactivity);
}
public void thirdbutton(View view){
final TextView thirdtext=(TextView) findViewById(R.id.thirdtext);
Bundle seconddata=getIntent().getExtras();
int vala=seconddata.getInt("one");
int valb=seconddata.getInt("two");
thirdtext.setText(vala + " " +valb);
}
}
The values a and b are not passed and the thirdtext does not change
Please help!!
You start your activity before you add the bundle to your intent.
Try it like this:
Intent z = new Intent(activitysecond.this, activitythird.class);
z.putExtras(bundle);
startActivity(z);
Replace this
EnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent z = new Intent(activitysecond.this, activitythird.class);
startActivity(z);
z.putExtras(bundle);
}
});
with
EnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent z = new Intent(activitysecond.this, activitythird.class);
z.putExtras("one", Integer.parseInt(editText1.getText().toString()));
z.putExtras("two", Integer.parseInt(editText2.getText().toString()));
startActivity(z);
}
});
Remove ClickListener for the edit texts and add the following lines in onClick of EnterButton
a = Integer.valueOf(editText1.getText().toString());
bundle.putInt("one",a);
b = Integer.valueOf(editText2.getText().toString());
bundle.putInt("two",b);
At the below; putExtra comes before startActivity, that is the mistake.
EnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent z = new Intent(activitysecond.this, activitythird.class);
startActivity(z);
z.putExtras(bundle);
}
});
try at below code;
EnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent z = new Intent(activitysecond.this, activitythird.class);
z.putExtras(bundle); // first
startActivity(z); //second
}
});
Also editText onClickListeners should not be implemented for your case. You should get the variables via:
if (editText1.getText() != null) { // to avoid exception
a = Integer.valueOf(editText1.getText().toString());
bundle.putInt("one",a);
}
if (editText2.getText() != null) { to avoid exception
b = Integer.valueOf(editText2.getText().toString());
bundle.putInt("two",b);
}
Modify your code like this:
EnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent z = new Intent(activitysecond.this, activitythird.class);
z.putExtras(bundle);
startActivity(z);
}
});
z.putExtras(bundle); must be higher that startActivity(z);
I have a code as follow.
MainActivity.java
package com.example.androidphpmy;
import com.example.androidphpmy.MainActivity;
import com.example.androidphpmy.R;
import com.example.androidphpmy.PaymentActivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnVacant1,btnVacant2,btnVacant3,btnVacant4,
btnVacant5,btnVacant6,btnVacant7,btnVacant8;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupMessageButton1();
setupMessageButton2();
setupMessageButton3();
setupMessageButton4();
setupMessageButton5();
setupMessageButton6();
setupMessageButton7();
setupMessageButton8();
}
private void setupMessageButton1(){
Button messageButton = (Button) findViewById(R.id.button1);
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"You clicked on block 1",Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this,PaymentActivity.class));
}
});
}
private void setupMessageButton2(){
Button messageButton = (Button) findViewById(R.id.button2);
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"You clicked on block 2",Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this,PaymentActivity.class));
}
});
}
private void setupMessageButton3(){
Button messageButton = (Button) findViewById(R.id.button3);
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"You clicked on block 3",Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this,PaymentActivity.class));
}
});
}
private void setupMessageButton4(){
Button messageButton = (Button) findViewById(R.id.button4);
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"You clicked on block 4",Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this,PaymentActivity.class));
}
});
}
private void setupMessageButton5(){
Button messageButton = (Button) findViewById(R.id.button5);
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"You clicked on block 5",Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this,PaymentActivity.class));
}
});
}
private void setupMessageButton6(){
Button messageButton = (Button) findViewById(R.id.button6);
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"You clicked on block 6",Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this,PaymentActivity.class));
}
});
}
private void setupMessageButton7(){
Button messageButton = (Button) findViewById(R.id.button7);
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"You clicked on block 7",Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this,PaymentActivity.class));
}
});
}
private void setupMessageButton8(){
Button messageButton = (Button) findViewById(R.id.button8);
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"You clicked on block 8",Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this,PaymentActivity.class));
}
});
}
}
Next is my payment page.
PaymentActivity.java
package com.example.androidphpmy;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RemoteViews;
public class PaymentActivity extends Activity {
Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
b = (Button)findViewById(R.id.Button01);
et = (EditText)findViewById(R.id.accountno);
pass= (EditText)findViewById(R.id.password);
tv = (TextView)findViewById(R.id.tv);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(PaymentActivity.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
payment();
}
}).start();
}
});
}
void payment(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://tanushreedutta.site40.net/payment_new/check.php");
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name
and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("accno",et.getText().toString().trim()));
// $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(newBasicNameValuePair("bpassword",pass.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if(response.startsWith("User Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(PaymentActivity.this,"Payment Successful",Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent(PaymentActivity.this, MainActivity.class));
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
PaymentActivity.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(PaymentActivity.this);
builder.setTitle("Payment Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
I have buttons in my MainAcitivity.java named as "V1,V2,...V8". Now I want such a functionality that if user clicks on "V1" and goes to payment page and payment is successful (PaymentActivity.java does payment part) then when its redirected to the MainActivity it should change my button from "V1" to "R1". Similarly for other buttons too. Any suggestions or advices will be highly appreciated. Thank you.
Whe you start PaymentActivity from MainActivity, start using startActivityForResult() and in MainActivity, write code to get the result send by PaymentActivity using setResults. Then according to the result, you can change the button text.
Another option is you can use sharedPreferences. In PaymentActivity, once payment is successful, set a sharedPreferences flag and after returning back to MainActivity, check that sharedprefernces flag and change the button accordingly.
I would prefer the first option. Hope it helps