Does data save once you leave an activity android - android

I have an application that populates a ListView with user input data from another Activity ; however, whenever I enter that data into the second Activity then return to the ListView activity I see it populated with the values I entered. But, if I return to the second activity again, enter the values, and go back to the ListView activity, I see the new values updated but the old ones have disappeared.
Now, I don't know if I'm not updating the listview correctly or if I need to use sqlite databases to store this data or shared preferences in order to update the listview to new data while containing the previous information.
Thanks for any help.
ListActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
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 com.personalproject.peter.timerapp.TestingForAlarmData.TestAlarm;
import java.util.ArrayList;
import java.util.List;
public class ListOfAlarms extends ActionBarActivity {
private static final int RESULT = 1000;
List<TestAlarm> alarms = new ArrayList<>();
String title;
int totalTime;
ListView listOfAlarms;
ArrayAdapter<TestAlarm> alarmArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_alarms);
final TextView emptyViewForList = (TextView) findViewById(R.id.emptyTextViewForList);
listOfAlarms = (ListView) findViewById(R.id.listView);
alarmArrayAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, alarms);
listOfAlarms.setAdapter(alarmArrayAdapter);
// if(listOfAlarms.getCount() <= 0){
// emptyViewForList.setText("No Alarms Currently Available");
// listOfAlarms.setEmptyView(emptyViewForList);
// }
listOfAlarms.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
alarms.get(position);
Intent clockDownActivity = new Intent(ListOfAlarms.this, CountDownAct.class);
clockDownActivity.putExtra("Title", title);
clockDownActivity.putExtra("totalTime", totalTime);
startActivity(clockDownActivity);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_list_of_alarms, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void goToFillOut(View view) {
Intent goingToFillOut = new Intent(this, Test.class);
startActivityForResult(goingToFillOut, RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == RESULT && resultCode == RESULT_OK){
title = data.getStringExtra("title");
totalTime = data.getIntExtra("totalTime", 0);
alarms.add(new TestAlarm(title, totalTime));
alarmArrayAdapter.notifyDataSetChanged();
}
}
}
SecondActivity
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Test extends ActionBarActivity {
private static final String LOGTAG = "Test.class";
private static final long timeInterval = 1000;
private Button complete;
private EditText titleEditText;
private EditText hourEditText;
private EditText minuteEditText;
private EditText secondEditText;
public static int hour;
public static int minute;
public static int second;
public static String title;
public int actualTimeFiniliazedInMilliSeconds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
titleEditText = (EditText) findViewById(R.id.titleEditText);
hourEditText = (EditText) findViewById(R.id.hourEditText);
minuteEditText = (EditText) findViewById(R.id.minuteEditText);
secondEditText = (EditText) findViewById(R.id.secondEditText);
complete = (Button) findViewById(R.id.completeButton);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void saveTimer(View view) {
if(titleEditText.getText().toString().isEmpty() || hourEditText.getText().toString().isEmpty()
|| minuteEditText.getText().toString().isEmpty() || secondEditText.getText().toString().isEmpty()) {
Toast.makeText(this, "Oops you forgot one", Toast.LENGTH_LONG).show();
return;
}
// complete.setVisibility(View.GONE);
title = titleEditText.getText().toString();
hour = Integer.parseInt(hourEditText.getText().toString().trim());
minute = Integer.parseInt(minuteEditText.getText().toString().trim());
second = Integer.parseInt(secondEditText.getText().toString().trim());
hour *= 3600000;
minute *= 60000;
second *= 1000;
actualTimeFiniliazedInMilliSeconds = hour + minute + second;
Intent intent = new Intent(Test.this, ListOfAlarms.class);
intent.putExtra("title", title);
intent.putExtra("totalTime", actualTimeFiniliazedInMilliSeconds);
setResult(RESULT_OK, intent);
finish();
}
}
Alarm.java
public class TestAlarm {
public String title;
public int totalTime;
public TestAlarm (String title, int totalTime) {
this.title = title;
this.totalTime = totalTime;
}
#Override
public String toString() {
return title;
}
}

It seems like you are replacing new list in listview rather to updating old list of listview.
When you come first time on activity A, you should create one global array list where you add all items which are added by user.
Now, when user go on Activity B and add any item, you should carry out value back to Activity A and add that item in list.
After adding that in list, you should notify data to Adapter. So, here your list will have 2 items and it will show on Activity A 2 items.

Related

ListView item deletion not happening

The aim is that store the string in the normal listview and then user touch(click) it move to next page along with user selected item. Once user click "Reject button" in the Operation.java, the should go-off from the List.java activity. It is not happening. It shows "Unfortunately, System has stopped".
MainActivity.java
public static int loop_exute=0 // first page variable
Intent i = new Intent(getApplicationContext(), List.class);
startActivity(i);
List.java
import android.R.string;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class List extends ActionBarActivity implements OnItemClickListener {
private ListView mainListView ;
private ArrayAdapter<String> listAdapter ;
Button buttonSum;
static String[] name;
ArrayList<String> planetList = new ArrayList<String>();
int pos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
mainListView = (ListView) findViewById( R.id.mainListView );
Bundle extras = getIntent().getExtras();
if(MainActivity.loop_exute==0) // acces 1st page value because the string array value sholuld load only once in its life time
{
MainActivity.loop_exute=MainActivity.loop_exute+2;
name = new String[] { "AAA", "BBB", "CCC", "DDD"
};
planetList.addAll( Arrays.asList(name) );
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, planetList);
mainListView.setAdapter( listAdapter );
//mainListView.getChildAt(0).setBackgroundColor(Color.RED);
show();
}
else // second time call
{
Intent intent = getIntent();
if(intent.hasExtra("MESSAGE"))
{
Bundle bd = getIntent().getExtras();
if(!bd.getString("MESSAGE").equals(null))
{
String object=bd.getString("MESSAGE");
int pos=planetList.indexOf(object);
planetList.remove(pos);
listAdapter.notifyDataSetChanged(); //show();
}
}
}
}
public void show()
{
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
Intent i = new Intent(getApplicationContext(), Operation.class);
i.putExtra("Value2",name[pos]);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}
Operation.java
reject = (ImageButton) findViewById(R.id.imageButton2);
reject.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), List.class);
i.putExtra("MESSAGE",value1); //send the list item value what we select in previous activity
startActivity(i);
}
});
In the setOnClickListener under Operation.java, you are trying to start another activity. Instead, insert code to manually destroy the activity. You can also use the finish() method. Here's a link to know more about it:
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

Android App Keeps Crashing When Attempting to Start New Activity

Unfortunately I have been banging my head against the wall for quite some time trying to figure out why the app crashes every time I press the "Display" button. As you can see an intent is called when the button is pressed, which should subsequently "change" to the GraphicDisplay Activity. Any help is appreciated.
package com.dwolford.app7;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.Spinner;
public class Main extends Activity {
Button quit;
Button display;
String word;
EditText wordEntry;
PopupMenu popupMenu;
Button colorScheme;
Spinner spin;
Integer[] items = new Integer[51];
int spinnerValue = 90;//The current value of the spinner which is selected by the user
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int spinnerValues = 50;
spin = (Spinner) findViewById(R.id.spinner);
for(int i = 0; i < 51; i++)//Populate spinner with values from 50 to 100
{
items[i] = spinnerValues;
spinnerValues++;
}
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,android.R.layout.simple_spinner_item, items);
spin.setAdapter(adapter);
spin.setSelection(40);
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Creating popup menu on button click
colorScheme = (Button)findViewById(R.id.colorScheme);
colorScheme.setOnClickListener(new View.OnClickListener() {
#Override
#SuppressLint("NewApi")
public void onClick(View v) {
popupMenu = new PopupMenu(Main.this, colorScheme);
popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());
popupMenu.show();
}
});
wordEntry = (EditText)findViewById(R.id.word);
display = (Button)findViewById(R.id.display);
display.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
word = wordEntry.getText().toString();//Get word String
Intent intent = new Intent(Main.this, GraphicDisplay.class);
int scale = (Integer)spin.getSelectedItem();
String colorSchemeVal = popupMenu.toString();
//Pass Word, scale, and colorscheme using intent
intent.putExtra("colorSchemeVal", colorSchemeVal);//Pass current value for color scheme
intent.putExtra("scale", scale);//Pass scale to Graphic Activity
intent.putExtra("word", word);//Pass word to Graphic Activity via intent
startActivity(intent);
}
});
quit = (Button)findViewById(R.id.quit);
quit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I think I see your problem. You call inside display ClickListener:
String colorSchemeVal = popupMenu.toString();
but you never initialize "popupMenu", unless you hit "colorScheme".

Getting Cast Exception Android

I'm creating a simple note app in android. I am basically using two activity classes named as Main Page and Second Activity. I'm storing some data in the shared preferences in second activity and want to use it in my first Activity. I'm storing data in shared preferences as (String,Integer) key-pair. In my main activity class, when i'm getting the value from shared preferences as Integer and compare it with value 0,i'm getting an exception that java.lang.string can't be cast to java.lang.integer. I don't know why this exception is coming. Android studio is not giving me an exception but when i run my app, my app crashes. I have attach the code for reference.
MainActivity class:
package com.example.prateeksharma.noteballondor;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class MainPage extends ActionBarActivity {
Notes notes = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main_page, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences("com.example.prateeksharma.noteballondor", Context.MODE_PRIVATE);
//Map<String, Integer> notesMap = (Map<String, Integer>)sharedPreferences.getAll();
List<Notes> listNotes = new ArrayList<>();
Map<String, ?> prefsMap = sharedPreferences.getAll();
for (Map.Entry<String, ?> entry: prefsMap.entrySet()) {
if (entry.getValue() == 0){
notes = new Notes();
}
notes.setNoteText(entry.getKey());
listNotes.add(notes);
sharedPreferences.edit().putInt(entry.getKey(),2);
}
NotesArrayAdapter notesArrayAdapter = new NotesArrayAdapter(this,R.layout.list_layout, listNotes);
final ListView listview = (ListView) findViewById(R.id.listView);
listview.setAdapter(notesArrayAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
/**/
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
notes = (Notes) parent.getItemAtPosition(position);
Intent intent = new Intent(MainPage.this, SecondActivity.class);
intent.putExtra("Notes",notes);
startActivity(intent);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch (item.getItemId()) {
case R.id.new_link:
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("Notes",(android.os.Parcelable)null);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
SecondActivity Class:
package com.example.prateeksharma.noteballondor;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
public class SecondActivity extends ActionBarActivity {
public SharedPreferences sharedPreferences;
SharedPreferences.Editor edit;
Notes notes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
sharedPreferences = getSharedPreferences("com.example.prateeksharma.noteballondor", Context.MODE_PRIVATE);
edit = sharedPreferences.edit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_second, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
notes = (Notes)intent.getParcelableExtra("Notes");
EditText editText = (EditText) findViewById(R.id.editText);
if(notes != null){
editText.setText(notes.getNoteText());
}
else{
editText.setText(null);
}
}
#Override
protected void onStop() {
super.onStop();
getIntent().removeExtra(notes.getNoteText());
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
Intent intent = getIntent();
//noinspection SimplifiableIfStatement
switch (item.getItemId()) {
case R.id.save:
EditText editText = (EditText)findViewById(R.id.editText);
if (notes != null){
edit.putInt(String.valueOf(editText.getText()),1);
}
else{
edit.putInt(String.valueOf(editText.getText()),0);
}
edit.commit();
return true;
case R.id.delete:
if(notes != null){
edit.remove(notes.getNoteText());
edit.commit();
finish();
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
}
Notes class that I'm using:
package com.example.prateeksharma.noteballondor;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by Dell on 02-06-2015.
*/
public class Notes implements Parcelable {
private String noteText;
public String getNoteText() {
return noteText;
}
public void setNoteText(String noteText) {
this.noteText = noteText;
}
private Notes(Parcel in) {
noteText = in.readString();
}
public Notes(){
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(noteText);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Notes> CREATOR = new Parcelable.Creator<Notes>() {
#Override
public Notes createFromParcel(Parcel in) {
return new Notes(in);
}
#Override
public Notes[] newArray(int size) {
return new Notes[size];
}
};
}
Can anybody tell me why this error is coming in MainActivity class at this line
if (entry.getValue() == 0)
Thank you..
Try to replace
if ((Integer)entry.getValue() == 0){
With
If((Integer.parseInt( entry.getValue()) ==0){

How to return list item selected to parent activity - android

I'm learning android development. And I trying to do the following:
An wellcome activity, with a TextView with the following text: "Please Select"
This Textview, has an OnClick Listener setted.
My intent is, when the user click on this textview, one new activity with a listview must be opened.
This listview cointains some values like: Country 1, Country 2, Country 3 and so on;
So, when the user select one value, this value must be returned to the parent activity.
In my parent activity I have the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
countrySamples = (TextView)findViewById(R.id.countrySamples);
countrySamples.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListCountrySelectedFragment whatKindOjectIsThis = new ListCountrySelectedFragment();
whatKindOjectIsThis.setListCountrySelectedActivityDelegate(new ListCountrySelectedFragment.ListCountrySelectedActivityDelegate() {
#Override
public void selectCountry(String name) {
selectItem(name);
}
});
}
});
}
[...]
public void selectItem(String name) {
int index = valuesArray.indexOf(name);
if (index != -1) {
countryButton.setText(name);
}
}
And I've created an blank fragment with a list.
And added the following code:
public static interface ListCountrySelectedActivityDelegate {
public abstract void selectCountry(String name);
}
private ListCountrySelectedActivityDelegate delegate;
[...]
But, my fragment is never started.. The true is.. I have to create a Fragment to this? Or, must by an activity? Or I'm totally wrong?
Thanks
Edited (complete code):
Login Activity:
package com.testenum_13;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.testenum_13.R;
import com.testenum_13.adapters.CountryAdapter;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.HashMap;
public class Login extends ActionBarActivity {
TextView countryButton;
private EditText codeField;
private int countryState = 0;
private ArrayList<String> countriesArray = new ArrayList<String>();
private HashMap<String, String> countriesMap = new HashMap<String, String>();
private boolean ignoreOnTextChange = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
countryButton = (TextView)findViewById(R.id.countryButton);
countryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent intent = new Intent(Login.this, CountrySelected.class);
CountrySelected fragment = new CountrySelected();
fragment.setCountrySelectActivityDelegate (new CountrySelected.CountrySelectActivityDelegate() {
#Override
public void countryWSelected(String name) {
selectCountry(name);
}
});
//startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void selectCountry(String name) {
int index = countriesArray.indexOf(name);
if (index != -1) {
ignoreOnTextChange = true;
codeField.setText(countriesMap.get(name));
countryButton.setText(name);
countryState = 0;
}
}
}
Country Activity:
package com.testenum_13;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.internal.widget.ActionBarOverlayLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.testenum_13.adapters.CountryAdapter;
import com.testenum_13.adapters.CountryAdapter.Country;
import java.util.List;
public class CountrySelected extends FragmentActivity {
public static interface CountrySelectActivityDelegate {
public abstract void countryWSelected(String name);
}
private CountryAdapter listViewAdapter;
private CountrySelectActivityDelegate delegate;
ListView countryList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_country_selected);
countryList = (ListView)findViewById(R.id.countryList);
listViewAdapter = new CountryAdapter(getBaseContext());
countryList.setAdapter(listViewAdapter);
countryList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Country country = null;
int section = listViewAdapter.getSectionForPosition(position);
int row = listViewAdapter.getPositionInSectionForPosition(position);
if (row < 0 || section < 0) {
return;
}
country = listViewAdapter.getItem(section, row);
if (position < 0) {
return;
}
if (country != null && delegate != null)
{
delegate.countryWSelected(country.name);
}
finish();
}
});
}
public void setCountrySelectActivityDelegate(CountrySelectActivityDelegate delegate) {
this.delegate = delegate;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_country_selected, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Thanks
You could use startActivityForResult(Intent, int) in the parent Activity and override onActivityResult() in the child activity. See this tutorial for more details on how to implent this pattern.

Get variables from one activity to another

I work simple android app for sending sms. I have 2 activities. One is main for sending 2 different messages with 2 different content but messages send to same number. On secund activity i have 3 fields: one is for input number to send messages, and other two are for message content. When I click save button app save user input and go back to main activity. And here start my problem. How can i send users input for number to send messages and messages content to main activity to send sms with saved user input? I am totally beginner with android developing so please help! Here is my MainActivity.java:
package com.example.davor.light;
import android.content.Intent; import
android.support.v7.app.ActionBarActivity; import android.os.Bundle;
import android.telephony.SmsManager; import
android.telephony.SmsMessage; import android.view.Menu; import
android.view.MenuItem; import android.view.View; import
android.widget.Button; import android.widget.ImageView; import
android.widget.TextView; import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// GUMBI INFORMACIJE
Button ukljuci = (Button) findViewById(R.id.ukljuci);
Button iskljuci = (Button) findViewById(R.id.iskljuci);
Button postavke = (Button) findViewById(R.id.postavke);
final ImageView slika = (ImageView) findViewById(R.id.slika);
// INFORMACIJA O PORUCI
final String broj = "097";
final String ukljuciPoruka = "Uključi";
final String iskljuciPoruka = "Isključi";
// KLIK NA GUMB ISKLJUČI
iskljuci.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(broj, null, iskljuciPoruka, null, null);
Toast.makeText(getApplicationContext(), "Isključeno! poslano na broj " + broj, Toast.LENGTH_LONG).show();
slika.setImageResource(R.drawable.off);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"Nemoguće isključiti!",Toast.LENGTH_LONG).show();
}
}
});
postavke.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent PostavkeActivity = new Intent(MainActivity.this,
Postavke.class);
startActivity(PostavkeActivity);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
} }
And here is code for my second activity from witch I want to pull users input to MainActivity:
package com.example.davor.light;
import android.app.Activity; import android.content.Intent; import
android.content.SharedPreferences; import
android.preference.PreferenceManager; import
android.support.v7.app.ActionBarActivity; import android.os.Bundle;
import android.view.Menu; import android.view.MenuItem; import
android.view.View; import android.widget.Button; import
android.widget.EditText; import android.widget.TextView; import
android.widget.Toast;
public class Postavke extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_postavke);
gumbZaPovratak();
SharedPreferences loadSettings = PreferenceManager.getDefaultSharedPreferences(this);
String ucitajBroj = loadSettings.getString("spremiBroj", "");
String ucitajUkljuci = loadSettings.getString("spremiUkljuci", "");
String ucitajIskljuci = loadSettings.getString("spremiIskljuci", "");
final EditText postavkeBroj = (EditText) findViewById(R.id.postavkeBroj);
postavkeBroj.setText(ucitajBroj);
final EditText postavkeUkljuci = (EditText) findViewById(R.id.postavkeUkljuci);
postavkeUkljuci.setText(ucitajUkljuci);
final EditText postavkeIskljuci = (EditText) findViewById(R.id.postavkeIskljuci);
postavkeIskljuci.setText(ucitajIskljuci);
Button spremi = (Button) findViewById(R.id.postavkeSpremi);
spremi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
spremiPostavke("spremiBroj", postavkeBroj.getText().toString());
spremiPostavke("spremiUkljuci", postavkeUkljuci.getText().toString());
spremiPostavke("spremiIskljuci", postavkeIskljuci.getText().toString());
Toast.makeText(getApplicationContext(), "Spremljeno", Toast.LENGTH_LONG).show();
finish();
}
});
}
private void postavkeBroj() {
EditText postavkeBroj = (EditText) findViewById(R.id.postavkeBroj);
}
private void spremiPostavke (String ključ, String vrijednost) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(ključ, vrijednost);
editor.commit();
}
private void gumbZaPovratak(){
Button nazad = (Button) findViewById(R.id.nazad);
nazad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_postavke, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
} }
You can use startActivityForResult()
You can refer this link:
http://hmkcode.com/android-startactivityforresult/
In Activity1
Intent myIntent = new Intent(this,Activity2.class);
myIntent.putExtra("var", variable_to_pass);
startActivity(myIntent);
In Activity2
Bundle extras = getIntent().getExtras();
if (extras != null) {
intentExtra = extras.getString("var"); // retrieving variable
}
You can add data to an intent like this :
String messageContent = (EditText) findViewById(yourMessageContentId).getText().toString();
String messageNumber = (EditText) findViewById(yourMessageNumberId).getText().toString();
intent.putExtra("com.example.davor.light.MESSAGE_CONTENT", messageContent);
intent.putExtra("com.example.davor.light.MESSAGE_NUMBER", messageNumber);
And then get it on the MainActivity :
Intent intent = getIntent();
String messageNumber = intent.getStringExtra("com.example.davor.light.MESSAGE_NUMBER");
String messageContent = intent.getStringExtra("com.example.davor.light.MESSAGE_CONTENT");
you can send information from one activity to other activity like bellow
Intent postavkeActivity = new Intent(MainActivity.this,
Postavke.class);
Bundle bundle=new Bundle();
bundle.putString(|"messageKey1", "message content1");
bundle.putString(|"messageKey2", "message content2");
postavkeActivity.putExtras(bundle);
startActivity(PostavkeActivity);
in main activity get bundle data like bellow
Bundle b=getIntent.getExtras();
String smsContent=b.getString("messageKey1");

Categories

Resources