I have no idea how to make my added view permanent with its own class saved for futeer access.
Right now when I run the code there will be an empty view since there are no values coming from the intents, once I click on the button and fill out the information, the empty box gets replaced with a view that has the title I had giving, but when I click to add again it just replaces the old one, how to ensure that it doesn't replace but gets added on?
//main_activiy
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sports_screen);
// Creating the list that is on screen
FloatingActionButton addClass = findViewById(R.id.Add_class_button);
//sending out variable
Intent intent = new Intent (this, Creating_Class_main.class);
Activity ma = this;
//names
Intent MB = getIntent();
String Classinp = MB.getStringExtra("strC");
String tchinp = MB.getStringExtra("strT");
//adding team
team sportsteam = new team(ma, Classinp,tchinp);
sportsteam.addtext();
// Input
addClass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(intent);
}
});
}
}
//Second activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_class);
EditText ClassName = findViewById(R.id.CLinput);
EditText teacher = findViewById(R.id.tchinput);
Button end = findViewById(R.id.end);
Intent intent = new Intent (this, MainActivity.class);
end.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent.putExtra("strC", ClassName.getText().toString());
intent.putExtra("strT", teacher.getText().toString());
startActivity(intent);
}
});
}
}
//my class
public class team {
// Defining Activity class to use
private Activity activity;
// Defining text box
LinearLayout lay;
View Tbox;
// Members Defining
String teamname;
String teacher;
ArrayList<Players> members = new ArrayList<Players>();
public team(Activity activity, String teamname, String teacher) {
// To be able to use activity
this.activity = activity;
// Normal things to define
this.teamname = teamname;
this.teacher = teacher;
// initialize the lay and Tbox variables
lay = activity.findViewById(R.id.Scontainer);
Tbox = activity.getLayoutInflater().inflate(R.layout.text_box_output, null);
}
public void addtext() {
// add text to the layout and view
TextView title = Tbox.findViewById(R.id.daTeam);
title.setText(teamname);
lay.addView(Tbox);
}
}
Related
I am trying to pass some data from one activity to another and I have made a toast in the other activity to see if data is being passed.When the toast shows up it is blank.I have done everything right and tried many different times with different methods I have also created another app but the problem still stays.It gives me null.
My java code in the first activity
public class titleandcuisine extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
public static final String TITLE_GET = "title";
public static final String CUISINE_GET = "cuisine";
ImageView imageView;
Button button;
Spinner spinner;
EditText dish;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_titleandcuisine);
dish = findViewById(R.id.editText);
spinner = findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.cuisines,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
button = findViewById(R.id.next);
imageView = findViewById(R.id.close);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), homepage.class));
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = dish.getText().toString();
String text2 = spinner.getSelectedItem().toString();
Intent data = new Intent(getBaseContext(),imagepost.class);
data.putExtra(TITLE_GET,text);
data.putExtra(CUISINE_GET,text2);
startActivity(data);
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Second activity java code
public class reviewactivity extends AppCompatActivity {
TextView cuisine,title;
ImageView displayimage,back;
Uri myUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reviewactivity);
Intent intent = getIntent();
String titleget = intent.getStringExtra(titleandcuisine.TITLE_GET);
String cuisineget = intent.getStringExtra(titleandcuisine.CUISINE_GET);
Toast.makeText(this, titleget + cuisineget, Toast.LENGTH_SHORT).show();
cuisine = findViewById(R.id.reviewcuisine);
title = findViewById(R.id.reviewtitle);
back = findViewById(R.id.backtopostvideo);
displayimage = findViewById(R.id.reviewdisplaimage);
// cuisine.setText(cuisineget);
// title.setText(titleget);
// myUri = Uri.parse(uri);
displayimage.setImageURI(myUri);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),videopost.class));
}
});
}
}
You need to read the text from the EditText when the button is clicked. Something like:
title = dish.getText().toString(); // Add this
Intent data = new Intent(getBaseContext(),imagepost.class);
data.putExtra(Intent.EXTRA_TEXT, title);
...
One more thing: You are trying to read the Intent.EXTRA_TEXT at the reviewactivity activity. However, nothing is starting that activity (at least within the piece of code that you shared).
I am new to Android development. I have an app in which the user creates multiple names (as if they were players of a game). These "players" appear as a matrix is used in the same activity. (Being possible here to exclude any player).
I want to display all of these players (MainActivity) in another activity (Main2Activity), showing only the first player added and, clicking a button, switch to the second player.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
RecyclerView recyclerView;
TextView textAdd;
EditText etAdd;
ArrayList<Model> models = new ArrayList<Model>();
MyAdapter myAdapter;
int position;
Button prox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prox = findViewById(R.id.prox);
prox.setOnClickListener(new View.OnClickListener() {
//next screen
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
String nome = etAdd.getText().toString();
intent.putExtra("value", nome);
startActivity(intent);
}
});
recyclerView = findViewById(R.id.recyclerView);
textAdd = findViewById(R.id.text_adicionar);
etAdd = findViewById(R.id.et_Adicionar);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
myAdapter = new MyAdapter(getApplicationContext(),
models, new MyAdapter.Onclick() {
#Override
public void onEvent(Model model, int pos) {
position = pos;
etAdd.setText(model.getId());
}
});
recyclerView.setAdapter(myAdapter);
textAdd.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.text_adicionar: {
insertItem(String.valueOf(etAdd.getText()));
}
break;
}
}
private void insertItem(String name) {
Gson gson = new Gson();
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", name);
Model model = gson.fromJson(String.valueOf(jsonObject), Model.class);
models.add(model);
myAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
Button play;
TextView text_player_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
play = findViewById(R.id.play);
text_player_name = findViewById(R.id.text);
play.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.play: {
String name = getIntent().getExtras().getString("value");
text_player_name.setText(String.valueOf(name));
}
break;
}
}
}
I'm not sure if I fully understand your question, but are you just looking for a way to pass data from one Activity to another?
If so, use .putExtra() with your Intent for starting the next Activity.
In the onCreate method for your second Activity, use .getExtras() to retrieve the data.
In 1st Activity
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("DataName", data);
startActivity(intent);
In the 2nd Activity
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
String[] dataArray = getIntent().getExtras().get("DataName"));
}
EDIT:
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
Button play;
TextView text_player_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
play = findViewById(R.id.play);
text_player_name = findViewById(R.id.text);
play.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String name = getIntent().getExtras().getString("value");
text_player_name.setText(String.valueOf(name));
}
I've got 2 activities (well actually 4 but only 2 matter for now), the main activity and the font changing activity. The main activity sends text that the user has typed in to the font changing activity using an intent and startActivityForResult. Within the font changing activity the user can change the font of the text, as expected. What I'm trying to do is after the user has changed the font, send the text and the new font back to the main activity. But I'm not sure how to do this. I'm thinking of using some kind of bundle but I am stuck. If anyone could help me that would be greatly appreciated.
Here's my (relevant) Main Activity code:
public class MainActivity extends AppCompatActivity
{
RelativeLayout move_group;
ImageView view;
String backgroundImageName;
SeekBar seekSize;
TextView user_text;
Button button;
SeekBar tiltChange;
String temp;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_text = (TextView) findViewById(R.id.user_text);
static final int REQUEST_FONT = 4;
public void FontChange(View view)
{
Intent fontIntent = new Intent(this, Main4Activity.class);
fontIntent.putExtra("Text", temp);
startActivityForResult(fontIntent, REQUEST_FONT);
}
//There's supposed to be an accompanying onActivityResult method as well
//but i haven't figured that part out yet
}
Here's my (relevant) Font Activity code:
public class Main4Activity extends AppCompatActivity
{
TextView user_font_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
user_font_text = (TextView) findViewById(R.id.user_font_text);
}
public void boldText(View view)
{
Typeface custom_font = getResources().getFont(R.font.avenir_next_bold);
user_font_text.setTypeface(custom_font);
}
public void italicText(View view)
{
Typeface custom_font = getResources().getFont(R.font.avenir_next_italic);
user_font_text.setTypeface(custom_font);
}
public void regularText(View view)
{
Typeface custom_font = getResources().getFont(R.font.avenir_next_regular);
user_font_text.setTypeface(custom_font);
}
public void thinText(View view)
{
Typeface custom_font = getResources().getFont(R.font.avenir_next_thin);
user_font_text.setTypeface(custom_font);
}
public void OK(View view)
{
//The intent and/or bundle would go here but I don't know what to do
}
}
public void FontChange(View view)
{
temp = user_text.getText().toString();
Intent fontIntent = new Intent(this, Main4Activity.class);
fontIntent.putExtra("Text", temp);
startActivityForResult(fontIntent, REQUEST_FONT);
}
this will fetch your string from textview to fontActivity.
Now in your FontActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
Intent intent = getIntent();
String text = intent.getStringExtra("temp");
user_font_text = (TextView) findViewById(R.id.user_font_text);
user_font_text.setText(text);
}
public void OK(View view)
{
Intent returnIntent = new Intent();
returnIntent.putExtra("result",
user_font_text.getText().toString());
returnIntent.putExtra("font",
ypur_font_type);
setResult(Activity.RESULT_OK, returnIntent);
}
Remaining part of setting font style can be done using SpannableStringBuilder. here you can check SpannableStringBuilder . Hope this helps.
public class MainActivity extends AppCompatActivity {
private Button addcar;
String[]foods={"carone","cartwo","carthree"};
#Override
protected void onCreate(Bundle savedInstanceState) {
if(savedInstanceState!=null){ <----- Here is where I thought I could get the updated array to be added to the listview.
String [] foods = savedInstanceState.getStringArray("foods");
ListAdapter myadapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,foods);
ListView mylistview = (ListView)findViewById(R.id.list);
mylistview.setAdapter(myadapter);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addcar = (Button) findViewById(R.id.button);
addcar.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myintent = new Intent("com.example.husse.profilesalgortihm.Main2Activity");
startActivity(myintent);
}
}
);
ListAdapter myadapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,foods);
ListView mylistview = (ListView)findViewById(R.id.list);
mylistview.setAdapter(myadapter);
mylistview.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (id == 0) {
Toast.makeText(MainActivity.this, foods[0], Toast.LENGTH_SHORT).show();
}
}
}
);
}
}
My Second activity
public class Main2Activity extends MainActivity {
public int number = 0;
public EditText Model;
public EditText Body;
public EditText color;
public String M;
public String B;
public String C;
private final String tag = "Main2activity";
private Button add;
Car_information[] cars = new Car_information[10];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Model = (EditText)findViewById(R.id.editText);
Body = (EditText)findViewById(R.id.editText2);
color = (EditText)findViewById(R.id.editText3);
add = (Button)findViewById(R.id.button2);
M = Model.getText().toString();
B = Body.getText().toString();
C = color.getText().toString();
// may run into issues with the final
add.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) { <--- Here is where I tried to save the information about the car but for the listview purpose I only wanted the name to be added to the Listview in the previous activity.
cars[number] = new Car_information();
cars[number].Model = M;
cars[number].Body = B;
cars[number].Color = C;
foods[number]= M;<----- Updating the array with the name the of the vehicle the user put in
number ++;
Intent intent = new
Intent(Main2Activity.this,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
);
}
#Override
public void onSaveInstanceState(Bundle outState) { <----- where I tried to save the new updated array to be used in the listview, so the user could see the new listview when the user goes back to the firstactivity.
super.onSaveInstanceState(outState);
outState.putStringArray("foods",foods);
}
What I am trying to do is when the user goes to the second activity he/she will enter in the information about his/her vehicle, but when they click the add button it will take them back to the previous activity and it will save the name of the car that they entered, and display it on the listview. But the list isn't being updated when they go back to the firstactivity.
You can use startActivityForResult() function to implement your task.
Example: You are in Activity1 and want to get data from Activity2.
In Activity1, call intent to start Activity2 with specific request
static final int PICK_CONTACT_REQUEST = 1; // The request code
...
private void pickContact() {
Intent pickContactIntent = new Intent(this, Activity2.class);
pickContactIntent.putExtra(...) <-- put some data to send to Activity2
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
then override onActivityResult like
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// get data sent from Activity2 via data parameter
}
}
}
In Activity2, when you're done with process, send data back to Activity1 by flow
setResult (int resultCode, Intent data) > finish()
this data will send to onActivityResult above
Hope it help !
FirstActivity.java
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName = (EditText) findViewById(R.id.etName);
btnOk = (Button) findViewById(R.id.btnOk);
btnOk.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Name = etName.getText().toString();
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
// Create a bundle object
intent.putExtra("NAME", Name);
startActivity(intent);
}
});
My Second Activity.java is as follows:
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
String UName;
String iName;
ListView lvName;
Button btnBack;
Bundle savedInstanceState;
#Override
protected void onCreate(Bundle b) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
b = getIntent().getExtras();
lvName = (ListView) findViewById(R.id.lvNames);
btnBack = (Button) findViewById(R.id.btnBack);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
UName=b.getString("NAME");
list.add(UName);
adapter.notifyDataSetChanged();
lvName.setAdapter(adapter);
lvName.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String item = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),
ThirdActivity.class);
// Create a bundle object
intent.putExtra("ITEMNAME", item);
startActivity(intent);
}
});
btnBack.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(intent);
}
});
}
My problem is whenever I click on back button, activity is restarted. So that first item in list is overwritten by second item. I want to get the output as list(items one by one) in second activity, whatever the data I enter in first activity. How can I do this?
For example when I enter ABC in edittext its displaying the same data ABC in list.Its good.
But when I click on back button and again enter any data in edittext its not displaying the data as second item in list but it is over writing the first item.This is the thing I wanna get to be solved...
You can put all items into intent in the first activity:
intent.putStringArrayListExtra(ITEMS, list);
And then you can extract them from intent in the second activity:
List<String> items = getIntent().getStringArrayListExtra(ITEMS);
use the extends Application class
public class MyGlobal extends Application {
public ArrayList<String> selectedAppsPackageNames = new ArrayList<String>();
}
for getting this in your activity
private MyGlobal mMyGlobal = (MyGlobal) getApplicationContext();
declare in manifest inside the Application Tag(give the path)
<application
android:name="com.afbb.lockaddicted.core.MyControlList"
..............
.........
</application>
You Just have to create the global list somewhere in your app like you can create Singletone or Application Class where you have to store your username List.
In below code you have to update your arrayList in first activity and you have to get your nameList in SecondActivity
public class MySingleton
{
private static MySingleton _instance;
private ArrayList<String> nameList;
private MySingleton()
{
}
public static MySingleton getInstance()
{
if (_instance == null)
{
_instance = new MySingleton();
}
return _instance;
}
public ArrayList<String> getNameList(){
return nameList;
}
public void setNameList(ArrayList<String> nameList(){
nameList = nameList;
}
}
You can save the names in the FirstActivity to shared preferences, with an id. Then retrieve those values in the SecondActivity. Also do not forget to clear the shared preferences when you destroy your FirstActivity.
FirstActivity
public class FirstActivity extends Activity {
private EditText etName;
private Button btnOk;
private String name;
private int id = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
etName = (EditText) findViewById(R.id.etName);
btnOk = (Button) findViewById(R.id.btnOK);
btnOk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
id++;
SharedPreferences.Editor editor = getSharedPreferences("shared_pref", MODE_PRIVATE).edit();
editor.putString(Integer.toString(id), etName.getText().toString());
editor.commit();
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
getSharedPreferences("shared_pref", MODE_PRIVATE).edit().clear().commit();
}
}
SecondActivity
public class SecondActivity extends Activity {
private ArrayList<String> list = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private String UName;
private String iName;
private ListView lvName;
private Button btnBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
lvName = (ListView) findViewById(R.id.lvNames);
btnBack = (Button) findViewById(R.id.btnBack);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
lvName.setAdapter(adapter);
SharedPreferences sharedPreferences = getSharedPreferences("shared_pref", MODE_PRIVATE);
Map<String,String> names = (Map<String, String>) sharedPreferences.getAll();
if(names != null){
for(String value: names.values()){
list.add(value);
}
adapter.notifyDataSetChanged();
}
btnBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}