【问题标题】:Can't access super class members in android [closed]无法在android中访问超类成员[关闭]
【发布时间】:2012-09-15 21:18:18
【问题描述】:

在我的 android 项目中有一个小错误,我无法从 AsyncTask 子类访问 Super 类字符串变量,我收到以下错误

public class XyzActivity extends ListActivity {

    // JSON Node names
                private static final String TAG_CONTACTS = "results";
                private static final String TAG_ID = "id";
                private static final String TAG_NAME = "name";
                private static final String TAG_GENDER = "rating";
                private static final String TAG_ADDRESS = "formatted_address";
                private static final String TAG_REFERENCE = "reference";


                private static final String TAG_LOCATION = "location";
                private static final String TAG_TYPE="type";


    // contacts JSONArray
    JSONArray results = null;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Bundle extras = getIntent().getExtras();
        if (extras != null) {
           String location = extras.getString("TAG_LOCATION");

        // url to make request
        String url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=restaurents+in+"+location+"&sensor=true&key=AIzaSyD38pak_katUfSR92WE2_O2b9y0JSp5htA";
        }

        LoadData ld = new LoadData();
        ld.onPreExecute();
    new LoadData().execute();

    }

class LoadData extends AsyncTask<String, String, String>
    { 
    ProgressDialog pDialog;

protected void onPreExecute() {

pDialog = new ProgressDialog(Xyz.this); 
pDialog.setMessage("Populating list please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
}

    // Hashmap for ListView
        ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
    protected String doInBackground(String... args) {


        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();
        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of Results
            results = json.getJSONArray(TAG_CONTACTS);

            // looping through All Contacts
            for(int i = 0; i < results.length(); i++){
                JSONObject c = results.getJSONObject(i);

                // Storing each json item in variable
                String id = c.getString(TAG_ID);
                String name = c.getString(TAG_NAME);
                String formatted_address = c.getString(TAG_ADDRESS);
                String rating = c.getString(TAG_GENDER);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_ID, id);
                map.put(TAG_NAME, name);
                map.put(TAG_ADDRESS, formatted_address);
                map.put(TAG_GENDER, rating);

                // adding HashList to ArrayList
                contactList.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
            }    
        protected void onPostExecute(String file_url) {

        this.pDialog.cancel();
                // dismiss the dialog after getting all products
                    /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(Xyz.this, contactList,
                R.layout.listview_item_row,
                new String[] { TAG_NAME, TAG_ADDRESS, TAG_GENDER,}, new int[] {
                        R.id.txtTitle, R.id.txtTitle1, R.id.txtTitle3 });

        setListAdapter(adapter);

        // selecting single ListView item
        ListView lv = getListView();

        // Launching new screen on Selecting Single ListItem
        lv.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                // Starting new intent
                Intent in = new Intent(getApplicationContext(), ProfileViewActivity.class);

            }
        });

        }

}
}

错误是

JSONObject json = jParser.getJSONFromUrl(url);

我无法从 onCreate() 方法调用 url 字符串,谁能修复这个错误?

【问题讨论】:

  • 我不明白错误是什么。

标签: android class string-concatenation


【解决方案1】:

onCreate...之前定义字符串

public class XyzActivity extends ListActivity {

// JSON Node names
            private static final String TAG_CONTACTS = "results";
            private static final String TAG_ID = "id";
            private static final String TAG_NAME = "name";
            private static final String TAG_GENDER = "rating";
            private static final String TAG_ADDRESS = "formatted_address";
            private static final String TAG_REFERENCE = "reference";


            private static final String TAG_LOCATION = "location";
            private static final String TAG_TYPE="type";


// contacts JSONArray
JSONArray results = null;

private String url = "";


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
       String location = extras.getString("TAG_LOCATION");

    // url to make request
    url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=restaurents+in+"+location+"&sensor=true&key=AIzaSyD38pak_katUfSR92WE2_O2b9y0JSp5htA";
    }

    LoadData ld = new LoadData();

new LoadData().execute();

}

class LoadData extends AsyncTask<String, String, String>
{ 
ProgressDialog pDialog;

protected void onPreExecute() {

pDialog = new ProgressDialog(Xyz.this); 
pDialog.setMessage("Populating list please wait...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    pDialog.show();
}

// Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
protected String doInBackground(String... args) {


    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();
    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);

    try {
        // Getting Array of Results
        results = json.getJSONArray(TAG_CONTACTS);

        // looping through All Contacts
        for(int i = 0; i < results.length(); i++){
            JSONObject c = results.getJSONObject(i);

            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            String formatted_address = c.getString(TAG_ADDRESS);
            String rating = c.getString(TAG_GENDER);

            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(TAG_ID, id);
            map.put(TAG_NAME, name);
            map.put(TAG_ADDRESS, formatted_address);
            map.put(TAG_GENDER, rating);

            // adding HashList to ArrayList
            contactList.add(map);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
        }    
    protected void onPostExecute(String file_url) {

    this.pDialog.cancel();
            // dismiss the dialog after getting all products
                /**
     * Updating parsed JSON data into ListView
     * */
    ListAdapter adapter = new SimpleAdapter(Xyz.this, contactList,
            R.layout.listview_item_row,
            new String[] { TAG_NAME, TAG_ADDRESS, TAG_GENDER,}, new int[] {
                    R.id.txtTitle, R.id.txtTitle1, R.id.txtTitle3 });

    setListAdapter(adapter);

    // selecting single ListView item
    ListView lv = getListView();

    // Launching new screen on Selecting Single ListItem
    lv.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            // Starting new intent
            Intent in = new Intent(getApplicationContext(), ProfileViewActivity.class);

        }
    });

    }

}
}

【讨论】:

  • 现在我得到一个运行时错误“FATAL EXCEPTION: AsyncTask #2”,“执行doInBackground()时发生错误”
  • 你能告诉我导致错误的行吗?顺便说一句,删除该行( ld.onPreExecute();) 无需调用它,因为当您执行任务时它将被自动调用..
  • 我已经删除了您在上面指定的语句,但我仍然遇到同样的错误
  • 09-24 15:58:35.233: E/AndroidRuntime(1144): 在 java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 09-24 15:58: 35.233: E/AndroidRuntime(1144): 在 java.util.concurrent.FutureTask.setException(FutureTask.java:124)
  • 你的完整 logcat。这是android内部的东西,没用
【解决方案2】:

url 是来自 onCreate 方法的局部变量。它甚至不应该在这种状态下编译。 (更不用说它可以是未定义的并且你的 AsyncTask 仍然被执行)。

你需要将url作为参数传递给execute方法:

new LoadData().execute(url);

然后在 AsyncTask 中,你可以获取它:

String url = args[0];

此外,从 AsyncTask 返回 null 并不是很有用,最好返回您获取的元素数组。

【讨论】:

  • 09-24 15:58:35.233:E/AndroidRuntime(1144):致命异常:AsyncTask #2 09-24 15:58:35.233:E/AndroidRuntime(1144):java.lang。运行时异常
猜你喜欢
  • 2012-10-06
  • 2023-04-04
  • 2013-06-08
  • 1970-01-01
  • 2011-06-21
  • 1970-01-01
  • 1970-01-01
  • 2022-11-30
  • 2012-12-21
相关资源
最近更新 更多