简体   繁体   中英

How to access a variable from another class? android java

Have spent hours trying to figure out why the " finalURL " variable in the "fetch" method cannot be read by the " Downloader " class? Would really appreciate any pointers..

It's a vocabulary improvement application, so it fetches XML data from a dictionary api.

public class DefineWord extends Activity {

    static final String head = new String("http://www.dictionaryapi.com/api/v1/references/collegiate/xml/");
    static final String apikey = new String("?key=xxxxxx-xxx-xxx-xxxx-xxxxx");

    TextView src;
    EditText searchBar;

OnCreate:

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.defineword);

        src=(TextView)findViewById(R.id.textFromWeb);
        searchBar = (EditText)findViewById(R.id.searchBar);
    }

fetch method:

    public void fetch(View v){                                              //onClick in xml starts this "fetch" method

        String w = searchBar.getText().toString();                          // get the text the user enters into searchbar
        String finalURL = head.trim() + w.trim() + apikey.trim();           //concatenate api url 

        Downloader d = new Downloader(); 
        d.execute(finalURL);                                                // Calls AsyncTask to connect in the background.    
}

AsyncTask:

    class Downloader extends AsyncTask<String,Void,String>{

        ArrayList<String> information = new ArrayList<String>();    // Store fetched XML data in ArrayList

        public String doInBackground(String... urls) {
            String result = null;

            try {

                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();

The problem is here. " finalURL " cannot be resolved to a variable.

                Document doc = builder.parse(finalURL);  //finalURL cannot be resolved to a variable ??? 

                doc.getDocumentElement().normalize();

                NodeList nList = doc.getElementsByTagName("entry"); // Make a list of all elements in XML file with tag name "entry" 

                for (int temp = 0; temp < nList.getLength(); temp++) {   //Iterate over elements and get their attributes (Definition, etymology...)  

                    Node nNode = nList.item(temp);

                    if (nNode.getNodeType() == Node.ELEMENT_NODE){


                        Element eElement = (Element) nNode;

                        String element = ("\nCurrent Element : " + eElement.getAttribute("id"));
                        information.add(element);  //

                        String definitions = ("\nDefinition : \n" + eElement.getElementsByTagName("dt").item(0).getTextContent());
                        information.add(definitions);
                    }

                }

            }catch (ParserConfigurationException e){
                e.printStackTrace();

            }catch(SAXException e){
                e.printStackTrace();
            }catch(IOException e){
                e.printStackTrace();
            }

            return result;
        }

        protected void onPostExecute (String result){

            String finalresult = information.toString();
            src.setText(finalresult);
        }

    }
}

Thanks for your time.

This is called a parameter. By using asyncTask.execute(parameter) you pass in the objects to doInBackground(String... arrayOfParameters) .

So to access the value again, you should use builder.parse(urls[0]);

finalURL is declared inside the fetch method and therefore can only be accessed within this function.

If you want it to be accessible throughout the program declare it outside of the function like so.

class MyClass{
    public static String finalURL;    // variable declaration

    public void fetch(View v){ 
        finalURL = head.trim() + w.trim() + apikey.trim();   // variable assignment
    }    

    public void otherFunction(){
        Document doc = builder.parse(finalURL);    // retrieves static class variable
    }
}

I hope this answers your question. If not, let me know what the confusion is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM