How to pass data from an activity to a java class - java

I have reached the wall on the following. I am trying to pass a variable from my main activity to a java class that generates my database because I want to use this variable in one of my queries of that database to get a result and then pass it to the Main activity. Here's my piece of code:
//MainActivity
public class MainActivity extends AppCompatActivity {
private static RadioGroup selectedAvgStds;
...... //rest of the code///
public void onClickListenerButton(){
selectedAvgStds = (RadioGroup)findViewById(R.id.controlAverageOfLiving);
showResults.setOnClickListener(
int avgStdLiving = selectedAvgStds.getCheckedRadioButtonId();
selectedAvgStdsRb = (RadioButton) findViewById(avgStdLiving);
//variable that I want to pass
String avgStdLivingText = (String) selectedAvgStdsRb.getText();
switch (option) {
case "one":
Intent intent = new Intent(MainActivity.this,DatabaseHelper.class);
Intent.putExtra("values",avgStdLivingText);
startActivity(intent);
break;
}
);
}
Piece of code of my database
//DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper{
public Cursor showResults(){
SQLiteDatabase db = this.getWritableDatabase();
//the intent does NOT work
Bundle bundle = getIntent().getExtras();
Cursor results = db.rawQuery("select * from "+TEMP_TABLE+"where value = " + selectedAvgStds , null);
return results;
}
}
The intent is not working despite the fact I have imported all the Intent libraries in the activity and the class. How can I achieve my goal? Why the Intents do not work here?
Any suggestion and idea will be enormously appreciated.

As per your comment, why do you not simply make DatabaseHelper an instance variable and parameterize your showResults method as following:
public class MyActivity extends Activity {
private DatabaseHelper myDatabaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//initialise your helper here
myDatabaseHelper = ...
}
public void onClickListenerButton(){
// All your other stuff here...
// variable that I want to pass
String avgStdLivingText = selectedAvgStdsRb.getText().toString();
myDatabaseHelper.showResults(avgStdLivingText);
}
}
And then within the helper class you can simply do:
public Cursor showResults(String selectedAvgStds){
SQLiteDatabase db = this.getWritableDatabase();
Cursor results = db.rawQuery("select * from "+TEMP_TABLE+"where value = " + selectedAvgStds , null);
return results;
}
}

The reason you are not able to get data using intent is that SQLiteOpenHelper class might not have the method definition for getIntent(). I would prefer you use Shared Preferences to store the data and retrieve it inside you SQLiteOpenHelper class.

Related

Pass widget input to DatabaseHelperSource file

Disclaimer: I am a newbie to Android development :)
How can I pass the string values collected from this first class to the class below? I attempted this but only got null values.
Here's my main activity.
public class Register extends AppCompatActivity {
protected SnapToSellDataSource mDataSource;
public String sFullname;
public String sEmail;
public String sMobileNumber;
public String sPassword;
EditText full_name, email, mobile_number, pwd, copwd;
Button registerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mDataSource = new SnapToSellDataSource(Register.this);
full_name = (EditText) findViewById(R.id.editText);
email = (EditText) findViewById(R.id.editText2);
mobile_number = (EditText) findViewById(R.id.editText3);
pwd = (EditText) findViewById(R.id.editText4);
copwd = (EditText) findViewById(R.id.editText5);
registerButton = (Button) findViewById(R.id.button);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Register register = new Register();
String editPassword = pwd.getText().toString();
String editConfirmPassword = copwd.getText().toString();
if(editPassword.equals(editConfirmPassword)) {
//This isn't overwriting the null class variables I
//instantiated so that I can pass them to the class below
sFullname = full_name.getText().toString();
sEmail = email.getText().toString();
sMobileNumber = mobile_number.getText().toString();
sPassword = pwd.getText().toString();
mDataSource.insertUser(register);
}
}
});
}
}
Here's the class that should receive the string values:
public class SnapToSellDataSource {
private SQLiteDatabase mDatabase;
private SnapToSellHelper mHelper;
private Context mContext;
public SnapToSellDataSource(Context context){
mContext = context;
mHelper = new SnapToSellHelper(mContext);
}
public void insertUser(Register register){
ContentValues values = new ContentValues();
values.put(SnapToSellHelper.COL_NAME, register.sFullname);
values.put(SnapToSellHelper.COL_EMAIL, register.sEmail);
values.put(SnapToSellHelper.COL_NUMBER, register.sMobileNumber);
values.put(SnapToSellHelper.COL_PASSWORD, register.sPassword);
mDatabase.insert(SnapToSellHelper.TBL_USERS, null, values);
}
}
I attempted to getText, getString from the second class but my app crashed maybe since the widgets were not yet assigned ids at the class level. Passing actual string values encased in quoation marks ("") works so it means the DatabaseHelper is properly set up.
I also tried declaring class variables and assigning the widget values to them but kept getting the "Cannot resolve symbol" error.
How you get a read from the local variables and pass them to the class variables that can then be set as public and read by another class; in this case, the second class?
You can not simply create instances of an activity in Android. Activities are not classes that you just do a “new” on and call their constructor. An instance of an Activity is created when the app starts or when an Intent starts an activity.
So doing this: Register register = new Register(); is not good! You can find good arguments here
Instead you can pass those values as parameters to the insertUser(params...) method or create a new User class and instantiate it with those string values and pass it to insertUser(user) method.
Method call:
mDataSource.insertUser(sFullname, sEmail, sMobileNumber, sPassword);
Method definition:
public void insertUser(String sFullname, String sEmail, String sMobileNumber, String sPassword) {
ContentValues values = new ContentValues();
values.put(SnapToSellHelper.COL_NAME, sFullname);
values.put(SnapToSellHelper.COL_EMAIL, sEmail);
values.put(SnapToSellHelper.COL_NUMBER, sMobileNumber);
values.put(SnapToSellHelper.COL_PASSWORD, sPassword);
mDatabase.insert(SnapToSellHelper.TBL_USERS, null, values);
}

Im missing some global variables

I've got 2 activities and a class that extends Application where I'm trying to store global variables with a kind of setter getter functions.
The main activity sets some views and a chart; then calls the second activity which should be setting values to be used afterwards on the previous chart.
Then pressing backbutton and returning to the previous activity onRestart is called and the chart is refreshed.
The problem is I lose my theorically global variables somewhere. Debugging i realized that the functions work perfectly fine while im adding values in the second activity but when I return to the first activity globalXCount returns '0' again. Why is that?
I think im missunderstanding some point regarding lifecycles.
I attach some fragments of the code.
First activity:
public class MainActivity extends Activity {
Global glObj = new Global();
CombinedChart mChart;
private int itemcount;
float displayed;
private final List<String> mMonthList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemcount = ((Global) this.getApplication()).getGlobalXCount();
displayed = itemcount/20;
mChart = (CombinedChart) findViewById(R.id.mchart);
populateHeaderList();
setChartSettings();
Intent intent = new Intent(MainActivity.this, QandA.class);
startActivity(intent);
}
#Override
protected void onRestart() {
super.onRestart();
itemcount = ((Global) this.getApplication()).getGlobalXCount();
displayed = itemcount/20;
populateHeaderList();
setChartSettings();
}
Second activity:
public class QandA extends Activity {
Global glObj = new Global();
ViewFlipper flipper;
private float lastX;
...
}else{
//TODO If all information if correctly filled
trainedmins = et1.getText().toString();
localLineValue = Integer.parseInt(trainedmins) * Integer.parseInt(statusQ1);
//Add values to lines
glObj.setLineXvalues(localLineValue);
// TODO Add new Bar value //
//Add 1 more value to count
glObj.addGlobalXCount();
}
...
Global class:
public class Global extends Application {
//TODO
public Integer globalXCount;
private List<Integer> lineXvalues = new ArrayList<>();
private List<Integer> barXvalues = new ArrayList<>();
//////
public Integer getGlobalXCount() {
if (this.globalXCount == null){
this.globalXCount = 0;
return this.globalXCount;
}else{
return this.globalXCount;
}
}
public void addGlobalXCount() {
if (this.globalXCount == null){
this.globalXCount = 0;
}else{
this.globalXCount = this.globalXCount + 1;
}
}
Thanks in advance.
First of all, register your custom Application context in AndroidManifest.xml within the <application>-tag.
<application
android:name="<your_package>.Global" ...>
Access the global application context within your activities like this:
Global glObj = (Global) getApplicationContext();
glObj.addGlobalXCount();
Do not create a new instance with new! Always retrieve the instance via getApplicationContext().
Furthermore, I would suggest you to initialize your class field glObj within the onCreate()-method of your Activities.

How to pass ArrayList of Custom objects to new activity?

I have created the class textViewTable In this class i am saving data related to TextViews That I want to Pass to Next Activity.
public class TextViewTable implements Serializable {
private String FONT;
private String TEXT;
private float TEXT_SIZE;
private ColorStateList TEXT_COLOR;
private float MARGIN_TOP;
private float MARGIN_BOTTOM;
private float MARGIN_LEFT;
private float MARGIN_RIGHT;
private Boolean BoldFlag;
private Boolean ItalicFlag;
private Boolean NormalFlag;
public TextViewTable(){
}
public TextViewTable(String FONT, String TEXT, float TEXT_SIZE, ColorStateList TEXT_COLOR, float MARGIN_TOP, float MARGIN_BOTTOM, float MARGIN_LEFT, float MARGIN_RIGHT, Boolean boldFlag, Boolean italicFlag, Boolean normalFlag) {
this.FONT = FONT;
this.TEXT = TEXT;
this.TEXT_SIZE = TEXT_SIZE;
this.TEXT_COLOR = TEXT_COLOR;
this.MARGIN_TOP = MARGIN_TOP;
this.MARGIN_BOTTOM = MARGIN_BOTTOM;
this.MARGIN_LEFT = MARGIN_LEFT;
this.MARGIN_RIGHT = MARGIN_RIGHT;
BoldFlag = boldFlag;
ItalicFlag = italicFlag;
NormalFlag = normalFlag;
}
}
From my activit i want to send ArrayList of Objects of TextViewTable class.
I have use the below function to send the ArrayList. But every time I am getting null pointer exception. Please Help to solve this.
public void onClick(View view)
{
Intent intent = new Intent(getApplicationContext(), displayImage.class);
Bundle bundleObject = new Bundle();
bundleObject.putSerializable("key", textViewsData);
intent.putExtras(bundleObject);
try {
startActivity(intent);
}catch (Exception e){
System.out.println(e);
}
}
};
Currently using Bundle.putSerializable for sending TextViewTable class object ArrayList to next Activity but not implementing Serializable interface in TextViewTable class:
public class TextViewTable implement Serializable{
....
}
you can follow ρяσѕρєя K's answer OR also you can do like below code:
public class GeneralClass{
public static ArrayList<TextViewTable> data = new ArrayList<TextViewTable>();
}
and then you can store your data in above arraylist on first activity like below:
Collections.copy(GeneralClass.data,textViewsData);
and now you can use GeneralClass.data arraylist in your second activity;
Sending the POJO from one activity to another acitivity:
Bundle bundle = new Bundle();
ArrayList<StatusData> passData = new ArrayList<StatusData>();
bundle.putSerializable("key", passData);
intent.putExtras(bundle);
startActivity(intent);
//then the transaction part
Getting the bundle`:
Bundle bundle = new Bundle();
bundle = getIntent().getExtras();
ArrayList<StatusData> dataReceived = (ArrayList<StatusData>)bundle.getSerializable("key"));
and then do whatever you like.Hope this helps.Cheers.
You can also use Parcelable.
First Activity
public void shareCustomArrayListObject(ArrayList<CUSTOMOBJECT> arrayList) {
if (arrayList != null && arrayList.size() > 0) {
Intent intent = new Intent(getApplicationContext(), displayImage.class);
Bundle bundleObject = new Bundle();
bundle.putSerializable("KEY", arrayList);
intent.putExtras(bundleObject);
}
}
Second activity where you want to retrieve the arraylist
private ArrayList<CUSTOMOBJECT> arrayList;
Bundle bundle=YOURACTIVITY.getBundle();
if(bundle==null){
bundle=getArguments();
}
if(bundle.getSerializable("KEY")!=null){
arrayList=(ArrayList)bundle.getSerializable("KEY");
}
and also if you have made a bean class for the arraylist
you need to implement
public class CUSTOMOBJECT implements Serializable{
and you done :)
you should use Parcelable object to pass data between activities as below:
Passing data from activity A to activity B
Intent intent=new Intent(A.this,B.class);
intent.putParcelableArrayListExtra("key", array_list);
startActivity(intent);
Getting data in Activity B from activity A
Intent intent=getIntent();
array_list = intent.getParcelableArrayListExtra("key");
So simple.
I hope this will help you.

My getter returns a wrong value

I'm programming an Android application and I got a little problem. I'm trying get a value from the Class A in the Class B but it doesn't return the correct value.
Here's my code to better understand (Sorry for my poor english)!
Class A
package com.androidhive.androidlistview;
//import
public class AndroidListViewActivity extends ListActivity {
int day;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
// Binding Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, adobe_products));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
day = Integer.parseInt(product.replaceAll("[^\\d.]", ""));
System.out.println(day);
//prints 1 When I click on the first list item, 2 When I click on the second, ...
startActivity(i);
// sending data to new activity
i.putExtra("product", product);
}
});
}
public int getDay() {
return day;
}
}
Class B
package com.androidhive.androidlistview;
//import
#SuppressLint({ "NewApi", "HandlerLeak" })
public class SingleListItem extends Activity {
AndroidListViewActivity alva = new AndroidListViewActivity();
int day;
String url;
String code;
//others variables
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Graphic
new NetworkOperation().execute();
}
class NetworkOperation extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... params) {
Document doc;
try {
day = alva.getDay();
System.out.println(day);
//prints 0
url = "http://www.planetehockey.com/calendrier.php?saison=45&div=9&club=&journee=" + day + "&jour=&mois=&page=0";
doc = Jsoup.connect(url).get();
//Récupère le texte d'une balise ayant bg_tableau pour class
Elements getId = doc.getElementsByClass("bg_tableau");
code = getId.text();
code = code + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
handler.sendEmptyMessage(1);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
//other code
}
};
}
Thank's a lot for all your answers it helped me a lot:
How I solved the problem:
Class A
i.putExtra("product", product);
startActivity(i);
and:
Class B
int day = Integer.parseInt(i.getStringExtra("product").replaceAll("[^\\d.]", ""));
In your Class A, you're trying to bundle components AFTER the activity has been called.
put the call function like this..
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
day = Integer.parseInt(product.replaceAll("[^\\d.]", ""));
System.out.println(day);
i.putExtra("product", product);
startActivity(i);
The passes the parameter in a bundle to the called activity.
HTH!
There are two simple solutions for your problem,
1. Pass day values in intent to SingleListItem
Or
2. Make day as a Static member and use it with class Name like,
public static int day; and access it `AndroidListViewActivity.day`
and remove public int getDay() method from AndroidListViewActivity as in both activity it refers a different object of AndroidListViewActivity .
Try doing i.putExtra("product", product); before startActivity(i);
In your Activity A you have written the getter method but not setter method to set the value of day in your code. Just write the setter method also and set the value of day.
public void setDay(int p_day)
{
day=p_day;
}
Make the variable day as static. After setting the day value try to get it in activity B.
I hope this will help you.

Accessing variables in different classes in Android

So say a user enters a total in an EditText field in my Incomings class, I then want this to be passed to my Results class. How do I go about this in Android? I know the best way is to use Accessor methods.
My Incomings class:
public void onClick(View v) {
String userLoan = etLoan.getText().toString();
String userGrant = etGrant.getText().toString();
String userFirst = etFirst.getText().toString();
float fUserLoan = Float.parseFloat(userLoan);
float fUserGrant = Float.parseFloat(userGrant);
float fUserFirst = Float.parseFloat(userFirst);
float totalIncomings = fUserLoan + fUserGrant + fUserFirst;
Intent intent = new Intent(v.getContext(), Outgoings.class);
startActivity(intent);
}
});
My results class has a blank function and will calculate the totals
I have tried using accessor methods in my MainAcivity class:
public float getTotalOutgoings() {
return totalOutgoings;
}
public void setTotalOutgoings(float totalOutgoings) {
this.totalOutgoings = totalOutgoings;
}
public float getTotalIncomings() {
return totalIncomings;
}
public void setTotalIncomings(float totalIncomings) {
this.totalIncomings = totalIncomings;
}
public float getTotalResult() {
return totalResult;
}
public void setTotalResult(float totalResult) {
this.totalResult = totalResult;
}
Any suggestions?
Pass Intent extras:
Intent intent = new Intent(v.getContext(), Outgoings.class);
intent.putExtra ("total",totalIncomings);
startActivity(intent);
Then access in your next Activity with
Intent i = getIntent();
float totalComings = i.getFloatExtra("total",-1.0);
Now about your Results class. It depends exactly what you want to do with that class. If all you need is a simple calculation, make a static method. And data passing is usually the other way around. The Activity calls a data class, gives it data, then the data class does whatever it needs to do and returns the result to the Activity.
use
Bundle bd = new Bundle();
bd.putFloat("key",value);
intent.putExtras(bd);
startActivityForResult(intent,1);
On other class
Bundle bund= getIntent().getExtras();
float value= bd.getFloat("key");
Are you trying to call a function on your MainActivity?
MainActivity m = (MainActivity) getActivity();
m.setTotalIncomings(XXX);

Categories

Resources