samedi 18 juin 2016

Android : Access one class variable data in another(by file or public variable)

I'm trying to get data from my mysql database into android app, so it can be used even when the phone is not connected to internet. For it, I use asynctask to run in background. Now the problem is that this code is written in other class, and the data is stored in a variable in that class. So I'm not able to access the contents of that variable outside the class at all. I have tried everything, like assigning it to a static variable of same type which is of other class, writing the data to file, sharedpreferences, but since the code is actually in a sort of function, I get errors with file operations and shared preferences. My code is as belows: public static boolean flag = false, otpStatus = false,otpcheckDone = false; public static SingleUser fromClient, fromServer; public static String resp; SharedPreferences sharedpreferences;

public static class LongOperation extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        if (getUserData) {
            getUserData = false;
            String METHOD_NAME = "user";
            SoapObject request = new SoapObject(
                    CommonData.NAMESPACE, METHOD_NAME);
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);
            envelope.setOutputSoapObject(request);
            HttpTransportSE androidHttpTransport = new HttpTransportSE(
                    CommonData.URL);
            try {
                androidHttpTransport.call(SOAP_ACTION, envelope);
                SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
                resp = resultsRequestSOAP
                        .getPrimitivePropertyAsString("return");
                upd = (UpdateData) stringToObject(resp);
                MainActivity.upd = upd;
                LoginActivity.setupd((UpdateData) stringToObject(resp));
                LoginActivity.upd = upd;
                addtoDatabase ad =new addtoDatabase(null, null, null, 1);
                addtoDatabase.firstTime=true;
                ad.addData(upd);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Do note that the UpdateData is a class accessed from a library file. Rest all works fine, I get response and all, but I'm just not able to access the variable,here 'upd', outside anywhere. As You can see, I have tried storing it in another class 'LoginActivity' variable LoginActivity.upd, but even that says that the object is null, although I can see the data in original "upd" when I do sysout.

So I need a way to access the data in "upd" variable outside the class. I call the function using:

CommonData.getUserData=true;
lo = new LongOperation();
lo.execute("");

Aucun commentaire:

Enregistrer un commentaire