Having Trouble Passing And Recieving Data From My Intent - java

I'm trying to make a pretty simple app to help my girlfriend feel safer.
Im really bad at this, and a little help would go a long way. I've been trying to work with intents, and I really feel as if I'm super close to the solution at hand, I just need a little help.
So, the opening page is supposed to wait until you have data in your shared Preferences and then it will act on it.
The second page is supposed to take some data from EditTexts and store it in your intent. For some reason though, my data is not being stored, and when I pull something from the intent it is "".
CLASS 1:
public void ActivateAlarm(View view){
Bundle myBundle = getIntent().getExtras();
if(myBundle == null){
Log.i("The bundle is empty!", "Smashing success!");
}
else{
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.jackson.distressalarm", Context.MODE_PRIVATE);
String NumberToCall = sharedPreferences.getString("CallNumber", "");
String TextOne = sharedPreferences.getString("1Text", "");
String TextTwo = sharedPreferences.getString("2Text", "");
String TextThree = sharedPreferences.getString("3Text", "");
Button myButton = (Button) findViewById(R.id.button);
myButton.setText(TextOne);
Log.i("MY NUMBER TO CALL", NumberToCall);
/*Take in the data from the settings. Check it for consistency.
1)Are the numbers empty?
2)Is the number 911 or a 7 digit number?
3)Do they have a passcode?
4)Is the number real? No philisophical BS
*/
}
}
CLASS 2:
public void GoToAlarm(View view){
EditText NumberToCall = (EditText) findViewById(R.id.callNumber);
EditText text1 = (EditText) findViewById(R.id.textNumOne);
EditText text2 = (EditText) findViewById(R.id.textNumTwo);
EditText text3 = (EditText) findViewById(R.id.textNumThree);
Intent intent = new Intent(this, AlarmActive.class);
intent.putExtra("callNumber", NumberToCall.getText().toString());
intent.putExtra("1Text", text1.getText().toString());
intent.putExtra("2Text", text2.getText().toString());
intent.putExtra("3Text", text3.getText().toString());
startActivity(intent);
}

I think the problem is coming from a bit of a mix-up between Intents and SharedPreferences.
An Intent is a way to pass data from one activity to another. You're passing data correctly in Class 2, but you're not retrieving it in Class 1. Here's how you can do that:
String NumberToCall = intent.getStringExtra("CallNumber");
String TextOne = intent.getStringExtra("1Text");
String TextTwo = intent.getStringExtra("2Text");
String TextThree = intent.getStringExtra("3Text");
SharedPreferences are a way to save user data. If you want to save data in addition to passing it between activities, you'll need to add it to SharedPreferences with the following code:
SharedPreferences preferences = this.getSharedPreferences("com.example.jackson.distressalarm", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("callNumber", NumberToCall.getText().toString());
editor.putString("1Text", text1.getText().toString());
editor.putString("2Text", text2.getText().toString());
editor.putString("3Text", text3.getText().toString());
editor.apply();
You can retrieve the values with the code you were using in Class 1.

Related

SharedPreferences If/Else Statement does not work correctly when I force close app

Summary of problem: When I force close the app by opening task window and swiping it closed my if/else statement is not working properly. I have the Name Selection Activity as the Default Launcher Activity. The name selection Activity should only pop up if there are no Shared Prefs, meaning the user has not selected a name yet from the spinner. But even after the user has selected a name and it is stored in Share Prefs, when I force close the app I still get returned to the name selection activity
What I have tried I have tried if (stringNamePackage.equals("")) and if (stringNamePackage == "") and if (NAME.equals("")) and if (NAME == "") At first I thought it was because maybe my Shared Prefs was not saving the name correctly but it is not that, the name still appears correctly when I force close it. But when I try to add the if/else statment it always just sends me back to the name selection activity regardless if I have a name saved in Shared Prefs or not. I have spent 4 hours trying to get this to work and I am at my wits end. I also spent hours looking at different stack articles of how to save and retrieve Shared Pref data. I even tried how to check the SharedPreferences string is empty or null *android and it is still not working.
NameSelectionActivity
public class NameSelection extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Spinner nameSpinner;
String stringNamePackage;
Button bSaveSelection;
Context context;
public ArrayAdapter<CharSequence> adapter;
public static String SHARED_PREFS = "sharedPrefs";
public static String NAME = "name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name_selection);
context = this;
nameSpinner = findViewById(R.id.horizonNameSpinner);
stringNamePackage = "";
//Create the list to populate the spinner
List<String> nameList = new ArrayList<>();
nameList.add("01");
nameList.add("02");
nameList.add("03");
//Array Adapter for creating list
//adapter = ArrayAdapter.createFromResource(this, R.array., android.R.layout.simple_spinner_item);
adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, nameList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
nameSpinner.setAdapter(adapter);
nameSpinner.setOnItemSelectedListener(this);
//If User has not selected name, start this activity to allow user to pick Name, else, send user to Main Activity
//else start MainActivity
if (stringNamePackage .equals("")) {
Toast.makeText(this, "Welcome, please select Name", Toast.LENGTH_LONG).show();
} else {
Intent sendToMainActIntent = new Intent(this, MainActivity.class);
startActivity(sendToMainActIntent);
}
//Save Selection Button Code
bSaveSelection = findViewById(R.id.bSaveSelection);
bSaveSelection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), MainActivity.class);
//Saves name to SharedPrefs
saveName();
//Sends user to MainActivity
startActivity(myIntent);
finish();
}
});
}
//Stores name selected in SharedPreferences
public void saveName() {
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = app_preferences.edit();
editor.clear();
//Stores selection in stringNamePackage
editor.putString(NAME, stringNamePackage );
editor.commit();
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//Put user selection into String text
String text = adapterView.getItemAtPosition(i).toString();
stringNamePackage = text;
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
Main Activity
The purpose of this activity case is to send the user back to the name Selection screen when they hit the "Test" button which will erase the shared prefs and hence, trigger the if/else statement and making the user pick a name. This is how I get and set the Name in Main Activity:
in onCreate
Getting name
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(context);
nameSharedPref = app_preferences.getString(NAME, "");
name.setText(nameSharedPref);
Clearing Name
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = mPrefs.edit();
editor.clear();
editor.commit();
finish();
What I expect: I expect the user to have to pick a name the first time they boot up the app. Then, every time they open the app an if/else statement will check if the user has a name or not in Shared Prefs. If they have a name they will go directly to the Main Activity. If they don't then they will go back to the Name Selection Activity.
To get data and store data to your SharedPreferences you use this:
SharedPreferences sharedPreferences = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
PreferenceManager.getDefaultSharedPreferences(context) is used to build "Settings" screens or similar, the first one you use it to store/retrieve arbitrary data not necessarily binded to UI.
Even more if you want to organize your SharedPreferences you could append to getPackageName() different keys like:
getSharedPreferences(getPackageName() + ".booleans", Context.MODE_PRIVATE);
getSharedPreferences(getPackageName() + ".flags", Context.MODE_PRIVATE);
getSharedPreferences(getPackageName() + ".keys", Context.MODE_PRIVATE);
each one of them is different file that stores shared preferences, you can ommit the prepending dot ., but for naming consistency it'll be better to keep it, there is no really need for the extra keys, but if you have some sort of OCD, that might be "relaxing" ;-).
Then you can use your Android Studio's Device Explorer to browse the shared preferences, they are located under "data/data/your.package.name/shared_prefs"

Using a combination of SQLite and SharedPreferences

I have ran into a problem. So I am trying to get data from my SQLite database based on the primary key and then I will display the row of data in separate textviews on another activity. Now, I have this working using Intents, but the problem is that I do not want to use "startactivity(intent)" for example as I do not want to go to the activity, I just want to send the data.
So, in context, I have 3 activities. the first activity the user fills in the information and click "verify" button(which saves to the db). this brings them to the second activity which will have an "Information" button on it and when this button is clicked on the next activity this is where I want to display the data I have retrieved from the database.
I have read and tried multiple posts, but does anyone know what the best option is for me to use? I am currently trying to use a combination of SQLite and SharedPreferences.
Code for activity 1 to get and save the data:
Button Progress1 = (Button) findViewById(R.id.progressBar);
Progress1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
res = myDb.getProgressBar1(); //gets the data from the database
if (res.moveToFirst()) {
String LTget = res.getString(res.getColumnIndex("LINETYPE"));
String PT = res.getString(res.getColumnIndex("PACKAGETYPE"));
String QTY = res.getString(res.getColumnIndex("QUANTITY"));
String DUR = res.getString(res.getColumnIndex("DURATION"));
String ST = res.getString(res.getColumnIndex("STARTTIME"));
String ET = res.getString(res.getColumnIndex("ENDTIME"));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(LTkey, LTget);
editor.putString(PTkey, PT);
editor.putString(qtykey,QTY);
editor.putString(durkey, DUR);
editor.putString(STkey, ST);
editor.putString(ETkey, ET);
editor.commit();
Intent intent = new Intent(Dashboard.this, Actforfragmentname.class); //takes me to the second activity
startActivity(intent);
Code to retrieve data: (unsure about getting from sharedpref so tried one line)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.verify_line);
myDb = new DatabaseHelper(this);
sqLiteDatabase = myDb.getReadableDatabase();
TextView LTTextView = (TextView) findViewById(R.id.textViewspinner1);
TextView PTTextView = (TextView) findViewById(R.id.textViewspinner2);
TextView QTYTextView = (TextView) findViewById(R.id.textViewQuantity);
TextView DURTextView = (TextView) findViewById(R.id.textViewDuration);
TextView STTextView = (TextView) findViewById(R.id.textViewStartTime);
TextView ETTextView = (TextView) findViewById(R.id.textViewendtime);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String LT =(sharedPreferences.getString(LTkey, LTget));
LTTextView.setText(LT);
PTTextView.setText(PT);
QTYTextView.setText(QTY);
DURTextView.setText(DUR);
STTextView.setText(ST);
ETTextView.setText(ET);
}
Can anyone help me out??
Thanks
You should use either Shared Preferences or SQLite database, the first one if you have a small amount of datas. The second one if it is bigger.
So You should push informations in database on button click in Activity 1, and retrieve them in Activity 3.
I got it working by using the method that I was trying out and that was using both SQLite and Shared Preferences together. I had to change the line of code that I was getting the sharedpreferences so to retrieve the data I know have:
SharedPreferences sharedPreferences = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
String LT = sharedPreferences.getString(LTkey, null);
String PT = sharedPreferences.getString(PTkey, null);
String QTY = sharedPreferences.getString(qtykey, null);
String DUR = sharedPreferences.getString(durkey, null);
String ST = sharedPreferences.getString(STkey, null);
String ET = sharedPreferences.getString(ETkey, null);

Is it possible to pass a int and a string both from one activty to another , if yes then how to achive it?

I am trying to send a string and a int type data from one activity to another but due to lack of knowledge i don't know how to do it.
With the particular coding given below now i can only send any one of the data type.
searched a lot but not found any answer appropriate for my question. If i have asked any thing wrong plzz notify me as i am new to android Dev.
Any help may be appreciated.
this is my java coding of the two activities :
First.java
public class QM extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qm);
}
public void FLG(View view) {
// Do something in response to button
EditText mEditText= (EditText)findViewById(R.id.editText1);
String str = mEditText.getText().toString();
Intent intent = new Intent(this, Q1.class);
intent.putExtra("myExtra", str);
startActivity(intent);
finish();
}
}
Second.java
public class Q1 extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_q1);
Intent intent = getIntent();
if (intent.hasExtra("myExtra")){
TextView mText = (TextView)findViewById(R.id.textView1);
mText.setText("user name "+intent.getStringExtra("myExtra")+"!"); }
}
}
You can send 2 extras or even more as long you have different keys for it, so in your problem you need 2 extras one for String and one for Integer.
sample:
pass:
Intent intent = new Intent(this, Q1.class);
intent.putExtra("myExtra", str);
intent.putExtra("myExtraInt", yourInt);
get:
Intent intent = getIntent();
if (intent.hasExtra("myExtra") && intent.hasExtra("myExtraInt")){
TextView mText = (TextView)findViewById(R.id.textView1);
mText.setText("user name "+intent.getStringExtra("myExtra")+"!");
int extraInt = intent.getIntExtra(myExtraInt);
}
I'd like to give you some information.
Imagine the Intent's extras to be a (theoretically) infinitely sized bagpack. You can put certain type of data into it in an infinite number as long as each of the data has a unique name which is a string.
Internally it's a table that maps names to values.
So: Yes you can put String and Int simultaneously into the Intent's extras like this.
String str = "Test";
int val = 2933;
Intent i = new Intent(MyActivity.this, NewActivity.class);
i.putExtra("MyStringExtraUniqueName", str);
i.putExtra("MyIntExtraUniqueName", val);
To check for it use i.hasExtra("MyStringExtraUniqueName") as you did already and to get it use i.getExtra("MyStringExtraUniqueName").
BUT if you only use getExtra you'll be returned data of type object. Remember to cast the returned value to the appropriate type or use one of the specialized getter methods for some predefined data types.
See this for the available getters: http://developer.android.com/reference/android/content/Intent.html
Bundle data = new Bundle();
data.putInt("intKey", 5);
data.putString("stringKey", "stackoverflow");
Intent i = new Intent(MyActivity.this, NewActivity.class);
i.putExtras(data);
//And in the second acitvity fetch this way
Bundle data = getIntent().putExtras(b);

Permenantly storing a string, by a user?

On my main activity I'm looking into a variable, if the variable contains a string ("example string") then it will go to the home-screen. if the variable contains nothing ("") it will redirect them to a page where they can enter a value via an editText and then permanently store it. So the next time they open the app, it will have this permanent string (until the app is deleted) and therefore it will just go to the home-screen.
From research i understand that i may have to use Shared Preferences. I have tried this already and I think im not doing something right.
Please could someone illustrate with a code example of what needs to be done for the code i have posted.
MainActivity.class
//this class uses the string, to see if its blank or contains a string
public class MainActivity extends Activity {
public static final String Verified = ""; //Originally comes blank
private EditText NumberET; //editText for user to enter a string
//the string verified is used in the main activity to determine which xml file to open.
Verified.class
// this is the class used to enter the string and permanently store it
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.verified);
Button VerifyCompleteButton = (Button) findViewById(R.id.VerifyCompleteButton);
VerifyCompleteButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String Verified;
String Number;
Bundle bundle = getIntent().getExtras();
Verified = bundle.getString("Verified");
NumberString = bundle.getString("NumberString")
Verified = NumberString.toString(); //set String Verified permenantly
}
});
You may use like this , Very much similar to above answer
For Saving String
SharedPreferences sharedPref = getSharedPreferences("App_Name_Prefs",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("Verified", Verified);
editor.commit();
For getting string
SharedPreferences shared = getSharedPreferences("App_Name_Prefs",
Context.MODE_PRIVATE);
String keyReturn = shared.getString(key, "");
Log.d("return value" , "Verified is " + verified);
Great example of using SharedPreference can be found on Google's Android developer website.
Saving data:
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("KEY", "VALUE");
editor.commit();
Get data:
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
String savedValue = context.getString("KEY", "");
Things to look after:
Make sure your [key] is the same for saving and getting. The shared preferences is a basically a hashmap/dictionary.
When getting use the second parameter to set a default return value when setting isn't found or set yet.

Sending Bundle/data to another class or screen

What am I doing wrong?
I've looked at other questions and thought I was doing the exact same things, but since its not working for me, obviously I'm doing something wrong!
I have my MainActivity.class that gets JSON data (coordinates) from a URL. This part works. I then want to load up a MapView, called OverlayActivity.class, and send this data to this map so I can populate it with overlays etc.
I pull varying numbers of points down and dynamically create buttons. Depending on what button is clicked, it sends different data.
Here's the code for this loop:
final LinearLayout layout = (LinearLayout) findViewById(R.id.menuLayout);
layout.removeAllViewsInLayout();
String itemName="";
int itemID=0;
for (int i = 0; i < dataSetsMap.size(); i++) {
itemID=i+1;
itemName=dataSetsMap.get(itemID);
Button b = new Button(this);
b.setText(itemName);
layout.addView(b);
// These need to be final to use them inside OnClickListener()
final String tempName=itemName;
final int tempID=itemID;
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent();
Bundle b = new Bundle();
i.setClass(myContext, OverlayActivity.class);
Log.i(TAG, "Setting extras: 1:"+tempName+" and 2:"+tempID);
b.putInt(tempName, tempID);
i.putExtras(b);
startActivity(i);
}
});
} // End for()
So obviously I want to read this data on the other side, assuming I'm sending it correctly. So, to read it, I've been trying a few different things:
//Method 1:
String test1=intent.getStringExtra("name");
String test2=intent.getStringExtra("id");
//Method 2:
String meh=getIntent().getExtras().getString("id").toString();
String bleh=getIntent().getExtras().getString("name");
//Method 3:
String value=savedInstanceState.getString("name");
String id=savedInstanceState.getString("id").toString();
//Method 4:
Bundle bundle = getIntent().getExtras();
String id=bundle.getString("id");
String value = getIntent().getExtras().getString("name");
i get a NullPointerException when trying to use any of these methods. Its my first time using these types of methods so can someone point me in the right direction or tell me where I've gone wrong?
Firstly, using Bundle b when you've already got Button b isn't really a good idea if for no other reason than it gets confusing, ;)
Secondly, you don't need to use a Bundle to pass a string and an int. Just add them to your Intent directly...
Intent i = new Intent(myContext, OverlayActivity.class);
i.putExtra("name", tempName);
i.putExtra("id", tempID);
startActivity(i);
To retrieve them in your OverlayActivity use...
Intent i = getIntent();
String name = i.getStringExtra("name");
int id = i.getIntExtra("id", -1); // -1 in this case is a default value to return if id doesn't exist
Why not just do this:
Intent i = new Intent();
i.setClass(myContext, OverlayActivity.class);
Log.i(TAG, "Setting extras: 1:"+tempName+" and 2:"+tempID);
i.putExtra("name", tempName);
i.putExtra("id", tempID);
startActivity(i);
and then you can fetch them with:
String name = getIntent().getStringExtra("name", "");
int id = getIntent().getIntExtra("id", 0);

Categories

Resources