How to Pass a Value from One Activity to Another Activity/Adapter - java

Iam trying to pass a value my Cartadapter to CartActivity.
My code is as follows:
CartActivity.java:
cartTotalChanged((cartAdapter.getTotal()));
CartAdapter.java:
public Double getTotal() {
Double total = 0d;
try{
for (MenuItem item : dataList)
total += item.getTotal();
}
catch(Exception e){
return total;
}
finally{
return total;
}
}
cartTotalChanged Function:
public void cartTotalChanged(Double totalAmount) {
if (coupon != null) {
totalAmount = totalAmount - (coupon.getType().equals("fixed") ? coupon.getReward() : ((totalAmount * coupon.getReward()) / 100));
}
DecimalFormat decimalFormat = new DecimalFormat("###.##");
subtotal.setText(decimalFormat.format(totalAmount) + currency);
double sc = (totalAmount * serviceCharge / 100);
feeService.setText(decimalFormat.format(sc) + currency);
total.setText(decimalFormat.format(totalAmount > 0 ? (totalAmount + sc + deliveryFee) : 0) + currency);
Helper.setCart(sharedPreferenceUtil, cartItems);
}
My problem here is cartTotalChanged((cartAdapter.getTotal())); is returning a Null and My app crashed with multiple thread failure.
kindly help

To pass data from adapter to activity use following way:
1.use Interface to create new interface class.
2.In activity implement that interface class and override passing data method.
3.In adapter class assign variable as inside parameter to interface method
Interface class:
Class Ainterface
{
public void passData(String setData);
}
Adapterclass:
Ainterface ainterface;
Adapterclass(Context context)
{
ainterface=context;
}
/*add below line in your onbind or onclick... whenever you want to pass data from adpter to activity use below line*/
ainterface.passData("set your variable which is load to activity");
Activity class:
Class MainActivity implements Ainterface
{
/*inside onCreate */
AdapterClass ac=new AdapterClass(this);
public void passData(String getdata)
{
Log.v("String is",getdata);
/*do something*/
}
}
i hope its work on you

You can create a class like below:
public class Globals{
private static Globals instance;
// Global variable
private Double cartTotal;
// Restrict the constructor from being instantiated
private Globals(){}
public void setData(Double d){
this.cartTotal=d;
}
public Double getData(){
return this.cartTotal;
}
public static synchronized Globals getInstance(){
if(instance==null){
instance=new Globals();
}
return instance;
}
}
Then on your adapter set it like this:
Globals g = Globals.getInstance();
g.setData(cartTotal);
And receive in your Activity as:
Globals g = Globals.getInstance();
Double cartTotal = g.getData();
You can set a number of Global variables like this as per your requirement.
Hope this helps !!

Related

android how to get value from the interface

I am getting values in broadcast receiver in MyFragment class which extends the interface DelayTime as -
if(intent.getAction().equals(BroadcastHelper.DEPARTURE_TIME)){
Bundle args = intent.getExtras();
if (args != null) {
int departure_time = args.getInt("Departure");
DepartureTime(departure_time);
}
}
else if(intent.getAction().equals(BroadcastHelper.ARRIVAL_TIME)){
Bundle args = intent.getExtras();
if (args != null) {
int arrival_time = args.getInt("Arrival");
ArrivalTime(arrival_time);
}
}
#Override
public int ArrivalTime(int arrival_time){
//what to do here
Log.d("hi","arrival_time" + arrival_time);
return arrival_time;
}
#Override
public int DepartureTime(int departure_time){
//what to do here
return departure_time;
}
I have an interface DelayTime -
public interface DelayTime {
public int ArrivalTime(int arrival_time);
public int DepartureTime(int departure_time);
}
I need to get the values from MyFragment class in MyOwn Class using the interface. In MyOwn class, the implementation which I have done is like -
DelayTime delaytime = new MyFragment();
int arri = delaytime.ArrivalTime(arr);
Log.d("hi","arrival 0" + arri);
myAdapter.setArrTime(arri); //Null pointer here
The value of arri is 0. The logs are like -
arrival_time 4500
arrival_time 0
Your interface DelayTime should look like this, for standards:
public interface Delayer {
void setArrivalTime(int arrivalTime);
void setDepartureTime(int departureTime);
}
When instantiating your MyOwn class you should pass MyFragment in its constructor and save a reference to it.
MyOwn mClass = new MyOwn((DelayTime) mFragment);
In the MyOwn class the constructor should be something like:
public MyOwn(DelayTime fragmentInterface) {
this.fragmentInterface = fragmentInterface;
}
Have the MyOwn class consume the interface methods:
public void setArrivalTime(int arrivalTime) {
fragmentInterface.setArrivalTime(arrivalTime);
}
And use the interface with your MyOwn object like this:
mClass.setArrivalTime(yourValue);
Also note that fragments are used with the (support) fragment manager and not instantiated directly like that.
I suggest you have a read here: https://developer.android.com/guide/components/fragments.html

import and use methods among different classes?

I created a method called calRoomCharges(int cusID) in the class public class transactions extends javax.swing.JFrame
Then I import this class to the class called public class AddReservation extends javax.swing.JFrame
I imported the class as follows.
import myhotel.FrontOffice.transactions;
these both classes are in the same project.
But when I'm going to call method calRoomCharges(int cusID) in AddReservation class it says that there is no such method.
I did this in netbeans.
So howshould I import the class and use the method that I created in another class?
here is the method I created
public double calRoomCharges(int cusId)
{
double tot=0.0;
try
{
//Get Rates
String sql="SELECT nights FROM reservation where cus_id ='"+cusId+"'";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
int nights = 0;
if(!rs.next())
{
//handle no result
}
else
{
nights = rs.getInt("nights") ;
}
//Get number of rooms
String sql2="SELECT no_of_rooms FROM reservation where cus_id ='"+cusId+"'";
pst=conn.prepareStatement(sql2);
rs=pst.executeQuery();
int rooms =0;
if(!rs.next())
{
//handle no result
}
else
{
rooms = rs.getInt("no_of_rooms") ;
}
//Get rates
String sql3="SELECT rates from room_type a,rooms b ,reservation r where a.type=b.type AND b.room_no=r.room_no AND r.cus_id='"+cusId+"' group by r.cus_id";
pst=conn.prepareStatement(sql3);
rs=pst.executeQuery();
double roomRates =0.0;
if(!rs.next())
{
//handle no result
}
else
{
roomRates = rs.getDouble("rates") ;
}
//Calculate room charges
tot =roomRates * rooms * nights;
}
catch(Exception e){}
return tot;
}
And this is the way I called it
private void EmpnamefieldMouseClicked(java.awt.event.MouseEvent evt) {
int cusNo =Integer.parseInt(cusID.getText());
double roomCharges = calRoomCharges(cusNo);
}
You simply have to either make the method static or call it through an object
public static double calRoomCharges(int cusId)
{
// ...
}
and call it like that:
double roomCharges = transactions.calRoomCharges(cusNo);
or call it through a created object:
transactions t = new transactions();
double roomCharges = t.calRoomCharges(cusNo);
And a good thing is to name classes with a first capital letter so you'd have class Transactions
You have 2 possibilities of calling the calRoomCharges method:
the method is a static method and you can call it via:
transactions.calRoomCharges(123);
the method is an object method, so you have to create an object first like:
transactions obj = new transactions();
obj.calRoomCharges(123);

How to use Arraylist over different classes

Im trying to add a dog (nyHund) which is created in a different class, to an Arraylist i created using a constructor in another class, but whenever i try to use the Arraylist in the "register" class, im getting the error that the arraylist name can't be resolved.
First class:
public class Hund {
private String namn;
private int ålder;
private double vikt;
private String ras;
public Hund(String hundnamn, int hundålder, String hundras, double hundvikt) {
this.namn = hundnamn;
this.ålder = hundålder;
this.ras = hundras;
this.vikt = hundvikt;
}
public String getNamn() {
return namn;
}
public int getÅlder() {
return ålder;
}
public double getSvanslängd() {
if (ras=="tax"){
return 3.7;
}else{
return ((vikt*ålder)/10);
}
}
public String toString() {
return namn + "\n" + ålder + "\n"+ras+"\n"+vikt+"\n"+getSvanslängd();
}
}
Second Class
import java.util.ArrayList;
public class testning {
public static void main(String[] args) {
Hund nyHund = new Hund("Daisy", 13, "labrador", 22.3);
System.out.println(nyHund.toString());
Register.läggTillHund(nyHund);
}
}
And the Third class:
import java.util.ArrayList;
public class Register {
public static void läggTillHund(Hund nyHund){
hundRegister.add(nyHund);
System.out.println(nyHund);
}
private Register(){
ArrayList<Hund> hundRegister = new ArrayList<Hund>();
}
}
The problem i am experiencing is with "hundRegister.add(nyHund)"
any thoughts? or pointers where im going wrong? (very new at Java)
Best Regards
Oskar
The ArrayList you've created is local to your Register constructor. Declare it inside the class, but outside the constructor, as an instance variable, so it's in scope throughout the class.
public class Register {
private ArrayList<Hund> hundRegister;
private Register(){
hundRegister = new ArrayList<Hund>();
}
}
Additionally, it's unclear why the constructor is private. Nothing else can access that constructor. I would make it public.
Also, in getSvanslängd, replace ras=="tax" with "tax".equals(ras). See How do I compare strings in Java?.

Getting value from one activity to another class

can anyone guide me to the right direction, as the situation is
have two classes calssA with Activity while classB is simple java class
1.classA has a editbox where the user inputs some value.
2.classB has a method that computes the user input.
need to get the user input value from classA to classB.
a).cannot get it through passing intent as the other class does not have activity.
b).have tried getter setter method by creating a class thus,calling setter where the user inputs the detail.
and calling the getter in another class.
Still the value is null, so what apparently is missing here.Any guidance to a example or brief explanation would be great.Thanks
You can use your own customized class to store the data and use it any where you need.
DataClass
public class Data {
private String a,b;
private static Data data= new Data( );
/* A private Constructor prevents any other
* class from instantiating.
*/
private Data (){ }
/* Static 'instance' method */
public static Data getInstance( ) {
return data;
}
public String getA()
{
return this.a;
}
public String getB()
{
return this.b;
}
public void setA(String a)
{
this.a = a;
}
public String getB(String b)
{
this.b = b;
}
}
In Activity
Data data = Data.getInstance()
data.setA("Stack");
data.setA("Overflow");
you can use this values in Java file like this
Data data = Data.getInstance()
System.out.println(data.getA());
System.out.println(data.getB());
according to my knowledge here you have to use singleton class.
public class DataHolderClass {
private static DataHolderClass dataObject = null;
private DataHolderClass() {
// left blank intentionally
}
public static DataHolderClass getInstance() {
if (dataObject == null)
dataObject = new DataHolderClass();
return dataObject;
}
private String _ProductNames;
public String get_ProductNames() {
return _ProductNames;
}
public void set_ProductNames(String _ProductNames) {
this._ProductNames = _ProductNames;
}
}
to set data
DataHolderClass.DataHolderClass.set_ProductNames(your data variable);
to get data
DataHolderClass.DataHolderClass.get_ProductNames(your data variable);
You can save the edittext value in SharedPreferences, thus making it available in all activity.
By doing this you can fetch the value in other activity without any hassle.
eg:
SharedPreferences.Editor editor = preferences.edit();
editor.putString("edtTextValue", valueOfEditText);
editor.commit();
Further fetching the value in other activity like this,
preferences.getString("edtTextValue", "");
In your activity class create
public static String valueEntered;
valueEntered=mEdtTxt.getText().toString();
and in your java class where you want
String enteredValue=ClassA.valueEntered;

How to return ArrayList from AsyncTask to another class?

i want to get Ftp folders list from server using AsyncTask and return folders names ArrayList to main class and update spinner adapter.
In main class i got spinner with adapter
//the array i want to update in AsyncTask
static ArrayList<String> directoriesTeacher = new ArrayList<String>();
//The adapter
createfile_spinTeacher = (Spinner) findViewById(R.id.createfile_spinTeacher);
final ArrayAdapter<String> dataAdapterTeacher = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,directoriesTeacher);
dataAdapterTeacher.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
createfile_spinTeacher.setAdapter(dataAdapterTeacher);
An in AsyncTask:
package com.nedoGarazas.learnanylanguage;
import java.util.ArrayList;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import android.os.AsyncTask;
import android.util.Log;
public class FtpTeacher extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
private static final String TAG = "MyFTPClient";
public FTPClient mFTPClient = null;
ArrayList<String> ftpTeacher = new ArrayList<String>();
#Override
protected ArrayList<String> doInBackground(ArrayList<String>... params) {
{
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect("host.ftp.com", 21);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login("admin", "admin");
if(status == true){
try {
FTPFile[] ftpFiles = mFTPClient.listFiles("/Wordsftp/");
int length = ftpFiles.length;
for (int i = 0; i < length; i++) {
String name = ftpFiles[i].getName();
boolean isDirectory = ftpFiles[i].isDirectory();
if (isDirectory) {
//adding to arraylist
ftpTeacher.add(name);
Log.i(TAG, "Yra : " + name);
}
else {
Log.i(TAG, "Directory : " + name);
}
}
} catch(Exception e) {
e.printStackTrace();
}
mFTPClient.setFileType(FTP.ASCII_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
}
}
} catch(Exception e) {
Log.d(TAG, "Error: could not connect to host ");
}
return ftpTeacher;
}
}
protected ArrayList<String>[] onPostExecute(ArrayList<String>... result) {
////How to return?
}
}
So how should i replace arraylist in AsyncTask with ArrayList in main class and update spinner updater dinamicly?
-- PSEUDO CODE --
Create a custom interface as followed:
public interface IAsyncTask {
void IAmFinished(ArrayList<Object> arrayList);
}
Add a constructor to your AsyncTask:
private IAsyncTask asyncTaskListener;
public MyAsyncTask(IAsyncTask asyncTaskListener){
this.asyncTaskListener = asyncTaskListener;
}
In your PostExecute of the AsyncTask:
public void onPostExecute(List<String> list) {
asyncTaskListener.IAmFinished(list);
}
In your Activity that starts your AsyncTask:
MyAsyncTask asyncTask = new MyAsyncTask(this);
asyncTask.execute(..);
Implement the interface:
public class MyActivity implements IAsyncTask
Implement the method:
public void IAmFinished(ArrayList<Object> list){
// Do whatever you want with your returned object
}
You already made your ArrayList static, make it public as well. and use that by your class name. and populate your ArrayList in onPostExecute(); like
protected void onPostExecute(ArrayList<String>... result) {
if(YourClassName.directoriesTeacher.size()>0)
{
YourClassName.directoriesTeacher.clear();
}
YourClassName.directoriesTeacher.addAll(result);
}
I assume you don't want a spinner while fetching data, but rather to fill your spinner with data from the background task? Returning data from AsyncTask commonly relies on this pattern, using interface.
1) Create an interface so that you can post back your results: (This class you can either create in separate file or just declare it in either class)
public interface ReturnData{
void handleReturnData(ArrayList<String> list);
}
2) Implement the ReturnData interface in your main class:
public class MyMainClass extends Activity implements ReturnData{
AsyncTask ftpTeacher = new FtpTeacher();//declare your async task
#Override
public void onCreate(Bundle savedInstanceState) {
ftpTeacher.returnData = this; //set this class as receiver for return data
//set up adapters etc, just like you do now
...
}
//Your new data will be returned here - update your current adapter with new list
#Override
void handleReturnData(ArrayList<String> list){
directoriesTeacher = list; //assign new data
dataAdapterTeacher.notifyDataSetChanged(); //Tell adapter it has new data = forces redraw
}
....
}
3) In your AsyncTask class:
public class FtpTeacher extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
private static final String TAG = "MyFTPClient";
public FTPClient mFTPClient = null;
ArrayList<String> ftpTeacher = new ArrayList<String>();
public ReturnData returnData; // <--- PUBLIC
...
}
4) Finally, to return data:
protected ArrayList<String>[] onPostExecute(ArrayList<String>... result) {
returnData.handleReturnData(result);
}
In your main, where you are calling your AsyncTask, overwrite the onPostExecute method and put your adapter stuff in there. It gets called on the UI Thread, so it's save.
So where you are calling the AsyncTask, do
new FTPTeacher() {
public void onPostExecute(List<String> list) {
createfile_spinTeacher = (Spinner) findViewById(R.id.createfile_spinTeacher);
final ArrayAdapter<String> dataAdapterTeacher = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);
dataAdapterTeacher.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
createfile_spinTeacher.setAdapter(dataAdapterTeacher);
}
}.execute();
onPostExecute methods runs in UI thread. You can assign the result in postexecute() to your arraylist in main method. Update the adapter by calling notifydatasetChanged to update your listview.
Implement a listener passing ArrayList and use this listener for returning your ArrayList.
public interface TaskListener {
public void onSuccess(ArrayList<String> result);
}
While invoking your async task for operation execution create an instance of TaskListener as follows:
TaskListener listener = new TaskListener() {
#Override
public void onSuccess(ArrayList<String> result) {
// Your result will come here
}
};
Pass this listenerobject as a parameter to the async task constructor. And create a global instance of TaskListener in the async task itself. Assign the TaskListener parameter in the constructor to the global instance.
Then in the onPostExecute of the async task class:
protected ArrayList<String>[] onPostExecute(ArrayList<String>... result) {
this.taskListenerGlobalInstance(result); // this will invoke the call back method
}
In your AsyncTask you could have a member (MyActivity m_activity) with the same class of your activity.
In your AsyncTask constructor, set a MyActivity parameter and record it in m_activity.
In your onPostExecute run a method of your activity that refresh your spinner adapter: m_activity.updateSpinner(ftpTeacher );

Categories