AppCompatActivity中的setListAdapter

时间:2015-09-23 06:38:59

标签: android android-studio

我的功能class repo { yumrepo { "datastax": descr => "DataStax Repo for Apache Cassandra", baseurl => "http://rpm.datastax.com/community", gpgcheck => "0", enabled => "1"; } } class { 'cassandra': cluster_name => 'foobar', listen_address => "${::ipaddress}", require => Yumrepo["datastax"], } include repo include cassandra 包含listArray,但我的代码中有错误

我的代码

NewsActivity

extends AppCompatActivity

在此

中出错
public class NewsActivity extends AppCompatActivity {

Toolbar toolbar;
// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> productsList;

// url to get all products list
private static String url_all_products = "http://localhost/update.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "updatedzc";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_VERSION = "version";
private static final String TAG_DESC = "description";

// products JSONArray
JSONArray products = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_news);

    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();
}
// Response from Edit Product Activity
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received
        // means user edited/deleted product
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }
}

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(NewsActivity.this);
        pDialog.setMessage("Loading News. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

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

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);
                    String version = c.getString(TAG_VERSION);
                    String description = c.getString(TAG_DESC);

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

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_VERSION, version);
                    map.put(TAG_DESC, description);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {
                Toast.makeText(getApplicationContext(), "doesn't have news now", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        NewsActivity.this, productsList,
                        R.layout.list_item, new String[] { TAG_PID,
                        TAG_NAME, TAG_VERSION, TAG_DESC},
                        new int[] { R.id.pid, R.id.name, R.id.timestamp, R.id.txtStatusMsg });
                // updating listview
                setListAdapter(adapter);
            }
        });
    }
}
}

像这样的错误

setListAdapter(adapter);

任何人都可以帮助我吗?

4 个答案:

答案 0 :(得分:6)

如果您的活动中有以下ListView

 <ListView android:id="@+id/mainListView"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:layout_below="@id/scan_content"/>

添加类似

的内容
public ListView mainListView;

到NewsActivity并替换

setListAdapter(adapter);

mainListView = (ListView) findViewById(R.id.mainListView);  
mainListView.setAdapter(adapter);

除非我误解了这个问题,否则这应该有用。

答案 1 :(得分:2)

只要您的布局中有一个带有ID的&#34; R.id.list&#34;

的ListView,此解决方案就可以正常工作

我填充ListView的方法

private void setWinesOnListView(){
        Log.d(TAG, "setWinesOnListView() was called.");

        wineCursor = db.getReadableDatabase().rawQuery("SELECT _ID, name, producer, varietal, vintage FROM wines ORDER BY name",null);
        @SuppressWarnings("deprecation")
        ListAdapter adapter = new SimpleCursorAdapter(this,R.layout.row,wineCursor, new String[]{DatabaseHelper.NAME,DatabaseHelper.PRODUCER,DatabaseHelper.VARIETAL,DatabaseHelper.VINTAGE},
                new int[]{R.id.name_row,R.id.producer_row,R.id.varietal_row,R.id.vintage_row});

        ListView mListView = (ListView) findViewById(R.id.list);
        mListView.setAdapter(adapter);
//        setListAdapter(adapter);
    }

答案 2 :(得分:1)

您无法使用setListAdapter(),因为AppCompatActivity不会从ListActivity继承。您需要自己将ListView添加到布局中,然后使用ListView.setAdapter()

答案 3 :(得分:0)

如果您想使用setListAdapter,则必须从ListActivity而不是AppCompatActivity更改

来扩展您的课程
public class NewsActivity extends AppCompatActivity {

public class MainActivity extends ListActivity {

在我的情况下,在扩展ListActivity后它没有显示错误。