I am sending the data between activities, through PutExtra. It's working perfectly.
The problem is when you click the back button, give an error and for the activity.
I've already tried to implement the StarActivityForResult option, and I can not get it to work.
Images below. Code "12345" is used as an example, and is sent to the three screens as PutExtra
Code:
Activity1:
public class MainActivity extends AppCompatActivity {
private Button btnIrAct2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnIrAct2 = (Button) findViewById(R.id.btnIrAct2);
btnIrAct2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent2 = new Intent(MainActivity.this, Activity2.class);
intent2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent2.putExtra("id_empresa", "12345");
startActivity(intent2);
}
});
}
}
Activity 2:
public class Activity2 extends AppCompatActivity {
private Button btnIrAct3;
private String mId_Empresa = null;
static final int SERVICO_DETALHES_REQUEST = 1;
private TextView tvResultado;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
/* Recebe id de outra tela*/
mId_Empresa = getIntent().getExtras().getString("id_empresa");
tvResultado = (TextView) findViewById(R.id.tvAct2);
tvResultado.setText(mId_Empresa);
btnIrAct3 = (Button) findViewById(R.id.btnIrAct3);
btnIrAct3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent3 = new Intent(Activity2.this, Activity3.class);
intent3.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent3.putExtra("id_empresa", "12345");
startActivityForResult(intent3, SERVICO_DETALHES_REQUEST );
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == SERVICO_DETALHES_REQUEST && resultCode == RESULT_OK) {
String resultBack = data.getStringExtra("id_empresa");
}
}
}
Activity 3:
public class Activity3 extends AppCompatActivity {
private String idEmpresa = null;
private TextView resultado;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
/* Recebe id de outra tela*/
idEmpresa = getIntent().getExtras().getString("id_empresa");
resultado = (TextView) findViewById(R.id.tvAct3);
resultado.setText(idEmpresa);
}
#Override
public void finish()
{
Intent data = new Intent();
data.putExtra("id_empresa", "12345");
setResult(Activity.RESULT_OK, data);
super.finish();
}
}
I need to resolve the conflict. Because on my return I need to send a data like PutExtra, at the same time that this Activity already has a piece of code that already receives a PutExtra.
If I understand the issue correctly, you should to use fragments instead of activities and save all the data in main activity but if you want to continue with this way try onBackPressed() method to choose what to do when the user pressed back button.
Insert this code in Activity 2
if(getIntent().getExtras().getString("id_empresa") != null)
{
mId_Empresa = getIntent().getExtras().getString("id_empresa");
}
Checking the data before setting it to the textview is must. If the string you are putting to textview is null, it will generate an error which will lead to crash.
Hope it helps!
Related
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.
I´m new to app development and I´m trying to figure out how to send an user input like name, to a list view located in a diferent activity.
Thanks in advance.
MainActivity:
public class MainActivity extends AppCompatActivity {
private Button mbuttonNext;
private EditText meditTextName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
meditTextName = (EditText) findViewById(R.id.editTextName);
mbuttonNext = (Button) findViewById(R.id.buttonNext);
mbuttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ClientList.class);
startActivity(intent);
}
});
}
}
ListViewActivity:
public class ClientList extends AppCompatActivity {
private ListView listaClientes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_list);
listaClientes = (ListView) findViewById((R.id.listView));
}
}
In the main activity you need to need intent.putExtra
mbuttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ClientList.class);
intent.putExtra("VariableName", "Fred");
startActivity(intent);
}
});
Than in listView
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_list);
listaClientes = (ListView) findViewById((R.id.listView));
Bundle bundle = getIntent().getExtras(); //get the intent and data passed
//next check that bundle is not null
if (bundle != null) {
String name = bundle.getString("VariableName");
//try loging out the value
Log.i("Name", name);
}
}
I believe this will solve your problem
When starting the new activity:
Intent newIntent = new Intent(MainActivity.this, ClientList.class);
newIntent.putExtra("com.example.myapp.NAME", "someName");
startActivity(newIntent);
Then in ClientList:
Intent intent = getIntent();
String name = intent.getStringExtra("com.example.myapp.NAME");
Can then use name variable as source data for the ListView.
Usually you should create an Adapter that will "set" the items in the ListView. In order for you to send/transfer the user input to another activity you can use "putExtra()". You can do that the following way:
intent.putExtra("str1",item)
where str1 is the key to get your item in the activity you started. To do that you should do:
Bundle b = getIntent().getExtras();
Obj a = (TypeCast) b.get("str1");
After that you should read how to create an Adapter and set it in a ListView in order for your ListView to show the item.
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 !
In the android sdk, I have programmed 2 buttons to bring me to 2 different layouts. However, only the first one I have programmed will work, while the second one will do completely nothing. I will provide the code if you can catch any things I missed, please tell me what you think. This is one of my first applications to run on android, so try to explain your suggestion as simple as you could.
Code:
public class MainActivity extends Activity {
private final String T = "Settings";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settingsButton();
}
private final String T2 = "ManualAdd";
protected void onCreate1(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
feederButton();
}
private void settingsButton() {
Button messageButton = (Button) findViewById(R.id.Settings);
View.OnClickListener myListener = new View.OnClickListener() {#
Override
public void onClick(View v) {
Log.i(T, "You clicked the settings button!");
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
}
};
messageButton.setOnClickListener(myListener);
}
private void feederButton() {
Button feedButton = (Button) findViewById(R.id.AddFeeder);
View.OnClickListener my2ndListener = new View.OnClickListener() {
public void onClick(View v) {
Log.i(T2, "You clicked the add button!");
startActivity(new Intent(MainActivity.this, ManualAdd.class));
}
};
feedButton.setOnClickListener(my2ndListener);
}
}
You cannot make a different onCreate() method for every button you have. The reason why only one of your Buttons work is because only the onCreate() method is only called. The system has no idea about onCreate1(). To get both of your buttons working change
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settingsButton();
}
to
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settingsButton();
feederButton();
}
You can completely delete onCreate1() from your source code, it is now obsolete.
It would also be a good idea to follow the official Android "First App" tutorial instead.
Try this code
public class MainActivity extends Activity {
Button Your_Button_Name;
Button Your_Button_Name;
Activity activity;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Your_Layout_Name);
//In (R.id.Your_Btn_Name) that's the name that you gave your button in the XML
activity = this;
Your_Button_Name = (Button) findViewById(R.id.Your_Btn_Name);
Your_Button_Name = (Button) findViewById(R.id.Your_Btn_Name);
Your_Button_Name.setOnClickListener(listener);
Your_Button_Name.setOnClickListener(listener);
}
private View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case (R.id.Your_Btn_Name):
startActivity(new Intent(MainActivity.this, Your_Layout_Name.class));
break;
case (R.id.Your_Btn_Name):
startActivity(new Intent(MainActivity.this, Your_Layout_Name.class));
break;
}
}
};
}