Adding to an array from a separate class - java

I have made a listView that is populated with an array. I can add data to this listview by entering in data in a textbox called txtinputs and then click a button called btnAdds this all works fine when I have it all in a single class. However what I want to do is have this on 2 separate screens using 2 separate classes, the txtinputs and the btnAdds in a separate class than the listView. When the data is entered into the txtinputs and the btnAdds is selected it will add that data into the listView on a seperate class. I want the listView in a class called ListDeadlines and my textBox and Button in a class called AddDeadline.
I currently add the data into the listView like this.
public ArrayList<String> arrayList;
public ArrayAdapter<String> adapter;
public EditText txtInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_deadlines);
final ListView listView = (ListView)findViewById(R.id.listv);
String[] items= {"HCI","ITM","Presentation"};
arrayList=new ArrayList<>(Arrays.asList(items));
adapter=new ArrayAdapter<String>(this,R.layout.list_item,R.id.txtitem,arrayList);
listView.setAdapter(adapter);
txtInput=(EditText)findViewById(R.id.txtinputs);
Button btAdd=(Button)findViewById(R.id.btnAdds);
btAdd.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String newItem=txtInput.getText().toString();
arrayList.add(newItem);
adapter.notifyDataSetChanged();;
}
});
}
I have tried to do it like this in my AddDeadline class like this however I get a runtime on the button click
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_deadline);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ListDeadlines lst= new ListDeadlines();
lst.txtInput=(EditText)findViewById(R.id.txtinput);
Button btAdd=(Button)findViewById(R.id.btnAdd);
btAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newItem = lst.txtInput.getText().toString();
lst.arrayList.add(newItem);
lst.adapter.notifyDataSetChanged();
}
});
}
I want to achieve something like this

In your ListDeadLinesActivity when a user hit the "+" button you want to start AddDeadlineActivity for a result.
You can put this code inside the onClick of that "+" button.
Intent intent = new Intent(this, AddDeadlineActivity.class);
startActivityForResult(intent, ADD_DEADLINE_REQUEST);
ADD_DEADLINE_REQUEST is the request code, you can declare a static int.
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
btAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent returnIntent = getIntent();
returnIntent.putExtra("result", yourEditText.getText().toString());
setResult(RESULT_OK,returnIntent);
finish();
}
});
}
In your ListDeadLinesActivity override onActivityResult method,
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ADD_DEADLINE_REQUEST){
if (resultCode == RESULT_OK) {
String item = data.getStringExtra("result");
arrayList.add(item);
adapter.notifyDataSetChanged();
}
}
}
Getting a Result from an Activity

Related

How manage data upload sent PutExtra

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!

Want to display stored name/value data in intent to new activity screen

I am semi-ok with the understanding of how you store and retrieve data through intents, what I am not sure about however is the code implementation. What I want to accomplish is to pass stored data (name/value pairs and a bundle object) to my ThirdActivity class from MainActivity class. Here is a snippet what i have attempted thus far (which when the user clicks on the a3button it just displays a blank page with no string):
MainActivity from which I want to store data to send to ThirdActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button a2_button = (Button) findViewById(R.id.a2_button);
a2_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent a2intent = new Intent("com.tester.lab.x");
startActivityForResult(a2intent, 1);
}
});
Button a3_button = (Button) findViewById(R.id.a3_button);
a3_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent a3intent = new Intent(v.getContext(), ThirdActivity.class);
a3intent.putExtra("greeting","my Name");
startActivity(a3intent);
}
});
}
}
ThirdActivity:
public class ThirdActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
getIntent().getStringExtra("greeting");
}
}
How would I display the string "my Name" once the user clicks ThirdActivity button? Any help is wonderful, thanks!
Everything is good, just add String type for value that you are getting and use this String as you want (to show in TextView else..):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
EditText text = (EditText) findViewById(R.id.your_textView_id);
String value = getIntent().getStringExtra("greeting");
text.setText(value);
}
Or by using Button:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
EditText text = (EditText) findViewById(R.id.your_textView_id);
Button three = (Button) findViewById(R.id.your_button_id);
three.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String value = getIntent().getStringExtra("greeting");
text.setText(value);
}
});
}

How to modify a string array and save it to use for a listview?

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 !

Android : How to save data (Intent's Data)

There is an example code that passed data by using Intent below the three Activity codes.
Activity A
public class A extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_A);
}
public void onButton1Clicked(View v) {
Intent intent = new Intent(getApplicationContext(), B.class);
startActivity(intent);
}
Activity B
public class B extends AppCompatActivity {
TextView tv;
ImageButton ib;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_B);
tv = (TextView) findViewById(R.id.textView);
ib = (ImageButton) findViewById(R.id.imageButton);
ib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(B.this, C.class);
startActivityForResult(intent, 2);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2) {
if (data != null) {
String message = data.getStringExtra("DATA");
tv.setText(message);
}
}
}
public void onButton2Clicked(View v) {
Intent intent = new Intent(getApplicationContext(), C.class);
startActivity(intent);
}
Activity C
public class C extends AppCompatActivity {
EditText et;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_C);
et = (EditText) findViewById(R.id.editText);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = et.getText().toString();
Intent intent = new Intent();
intent.putExtra("DATA", data);
setResult(2, intent);
finish();
}
});
}
The order of activity is A - B - C.
In A, there is a Button that can move to B, and in B there are a Button(can move to C) and TextView. In C, a Button(can move to B again) and EditText.
For example, Using 'startActivityForResult' I have output as TextView(B) that received a text which was input by EditText in C. But after moving B into A(Back), an insertion of TextView gets disappeared when entering to B again. In addition, even if entering into C, there is no insertion of EditText, too.
I would really need and know 'Save code' into variable by inputting as EditText when pressing a button in C.
In this case, HOW can I add ‘Code’ the remain the insertion value either the insertion value remains by quitting the application or moves to Activity that received DATA like A?
Thanks for your cooperation and concern.
To maintain the state of your activity, you have to override onSaveInstanceState method. Store the value of your TextViews and EditText in this method. For example, let's talk about Activity B. In activity B you would do something like this:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
String text = tv.getText().toString();
savedInstanceState.putString("mytext", text);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
Then in your onCreate do this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Set Content View and initialize the views
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
String mytext = savedInstanceState.getString("mytext");
tv.setText(mytext);
} else {
// Probably initialize members with default values for a new instance
}
...
}
You can read more about Recreating an Activity.
You can store intent's data using following way..
Your example seems confusing on how you passing the data and you have two methods in ActivityB handing the Intent. (onButtonClicked and StartActivityForResult())
Here's simple example
Define unique string to save your Intent's data in
- ActivityA
public final static String EXTRA_MESSAGE ="myMessage";
below method will open the ShowMessage Activity showing the message you type in EditText view.
public void sendMessage(){
Intent intent = new Intent(this, ShowMessage.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
Here's how you can retrieve that data in ShowMessage activity.
-ActivityB.
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
//EXTRA_MESSAGE is a unique string that holds the message typed in TextView
TextView receiveMessage = findViewById(R.id.sentMessage);
receiveMessage.setText(message); //would set the message typed in ActivityA
Now when you get back and if you still want your EditText to have the previous string entered, you can do as the answer given by Eric B.
//Saving the value
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
String myMessage = editText.getText().toString();
outState.putString("myMessage", myMessage);
}
in onCreate(), you can retrieve as follows
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null){
String myMessage = savedInstanceState.getString("myMessage","");
editText.setText(myMessage);
}
Also one thing recommended is resultCode == RESULT_OK for validation of intent.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2 && resultCode == RESULT_OK) {
if (data != null) {
String message = data.getStringExtra("DATA");
tv.setText(message);
}
}

How to retrieve data without using database,it has to display in listview

I am creating one dynamic list view i don't need database to store the data,whatever i am adding the data,it has to display in my list view. Right now its not displaying in my list view.
Projectlistactivity.java
public class Prayers extends ListActivity{
private static final int ACTIVITY_CREATE=0;
/** Items entered by the user is stored in this ArrayList variable */
ArrayList<String> list = new ArrayList<String>();
/** Declaring an ArrayAdapter to set items to ListView */
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prayers_list);
fillData();
registerForContextMenu(getListView());
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
//btn.setOnClickListener(listener);
/** Setting the adapter to the ListView */
setListAdapter(adapter);
}
private void fillData() {
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_insert:
createProject();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
private void createProject() {
Intent i = new Intent(this, PrayersEditActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_prayers_list, menu);
return true;
}
}
This is my projecteditactivity.java
public class PrayersEditActivity extends Activity{
private EditText mTitleText;
private Button mConfirmButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prayers_edit);
mTitleText = (EditText) findViewById(R.id.title);
mConfirmButton = (Button) findViewById(R.id.confirm);
registerButtonListenersAndSetDefaultText();
}
private void registerButtonListenersAndSetDefaultText() {
mConfirmButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//saveState();
String title = mTitleText.getText().toString();
mTitleText.setText("");
//adapter.notifyDataSetChanged();
setResult(RESULT_OK);
Toast.makeText(PrayersEditActivity.this, getString(R.string.task_saved_message), Toast.LENGTH_SHORT).show();
finish();
}
});
}
/*private void saveState() {
//mTitleText = (EditText) findViewById(R.id.title);
String title = mTitleText.getText().toString();
mTitleText.setText("");
adapter.notifyDataSetChanged();
}*/
}
In my listview if i click the menu button it has to go to the edit page,in their i have to add project after clicking the save button,it has to display in my listview,Right now its not display in my listview.
startActivityForResult(i, 1); and override this method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
list.add(result);
adapter.notifyDataSetChanged();
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
in your projecteditactivity.java change the onClick to following code
#Override
public void onClick(View view) {
String title = mTitleText.getText().toString();
mTitleText.setText("");
Intent returnIntent = new Intent();
returnIntent.putExtra("result",title);
setResult(RESULT_OK,returnIntent);
finish();
}
Why cant you store the data in a file, so that, you can retrive it when the application goes to background and after a few time, when come back, you can retrive it from file if memory lost happend.
I used to keep data in a Json formatted string, Dont know how and from where you get the list data.
you may use the life_cycle function. In addtion, you may transmit the data between Activities. So that you can use the edit data to display.
keep your data with ondestroy, onpause and onresume method.. and second option is to keep it with sharedprefence or sqlite.

Categories

Resources