平板电脑上的ListView

时间:2014-10-01 06:07:58

标签: java android eclipse listview

我有一个代码从数据库中检索并在listView中显示结果..当我试图复制代码并将其粘贴到另一个项目,这是平板电脑应用程序,它没有工作!为什么?有人可以告诉我吗?

这是我的java类

public class EditExs extends ListActivity {

// 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://www.lamia.byethost18.com/get_all_ex.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "ID_exercise";
private static final String TAG_NAME = "ID_exercise";

// products JSONArray
JSONArray products = null;

public String cha,lev;

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

    Intent i = getIntent();
     cha = i.getStringExtra("chapter");
     lev = i.getStringExtra("level");

        Log.d(null, cha);
        Log.d(null, lev);
    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();

    // Get listview
    ListView lv = getListView();

    // on seleting single product
    // launching Edit Product Screen
    lv.setOnItemClickListener(new OnItemClickListener() {

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


            // getting values from selected ListItem
            TextView t=(TextView) view.findViewById(R.id.pid);
            String pid =t.getText().toString();
            Intent in = new Intent(getApplicationContext(), EditEx.class);
            in.putExtra("ID", pid);
            startActivity(in);
        /*  // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    EditProductActivity.class);
            // sending pid to next activity

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);*/
        }
    });

}

// Response from Edit Product Activity
@Override
protected 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(EditExs.this);
        pDialog.setMessage("Loading products. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        String l=lev;
        String ch=cha;

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        //params.add(new BasicNameValuePair("ID_chapter", ch));
        //params.add(new BasicNameValuePair("level", l));

        // 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);

                    // 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);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        NewProductActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } 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(
                        EditExs.this, productsList,
                        R.layout.item_list_3, new String[] {TAG_NAME},
                        new int[] { R.id.pid});
                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}
 }

activity_edit_exs.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".ViewExs" >

 <ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

 </RelativeLayout>

item_list_3.xml

 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<TextView
    android:id="@+id/pid"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:visibility="visible" />


 </RelativeLayout>

我得到的错误是:

10-01 02:02:28.333: E/AndroidRuntime(923): FATAL EXCEPTION: main
10-01 02:02:28.333: E/AndroidRuntime(923): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anistat/com.example.anistat.AdminEditExs}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
10-01 02:02:28.333: E/AndroidRuntime(923):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-01 02:02:28.333: E/AndroidRuntime(923):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-01 02:02:28.333: E/AndroidRuntime(923):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-01 02:02:28.333: E/AndroidRuntime(923):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-01 02:02:28.333: E/AndroidRuntime(923):  at android.os.Handler.dispatchMessage(Handler.java:99)
10-01 02:02:28.333: E/AndroidRuntime(923):  at android.os.Looper.loop(Looper.java:137)
10-01 02:02:28.333: E/AndroidRuntime(923):  at android.app.ActivityThread.main(ActivityThread.java:5103)
10-01 02:02:28.333: E/AndroidRuntime(923):  at java.lang.reflect.Method.invokeNative(Native Method)
10-01 02:02:28.333: E/AndroidRuntime(923):  at java.lang.reflect.Method.invoke(Method.java:525)
10-01 02:02:28.333: E/AndroidRuntime(923):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-01 02:02:28.333: E/AndroidRuntime(923):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-01 02:02:28.333: E/AndroidRuntime(923):  at dalvik.system.NativeStart.main(Native Method)
10-01 02:02:28.333: E/AndroidRuntime(923): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
10-01 02:02:28.333: E/AndroidRuntime(923):  at android.app.ListActivity.onContentChanged(ListActivity.java:243)
10-01 02:02:28.333: E/AndroidRuntime(923):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:270)
10-01 02:02:28.333: E/AndroidRuntime(923):  at android.app.Activity.setContentView(Activity.java:1895)
10-01 02:02:28.333: E/AndroidRuntime(923):  at com.example.anistat.AdminEditExs.onCreate(AdminEditExs.java:56)
10-01 02:02:28.333: E/AndroidRuntime(923):  at android.app.Activity.performCreate(Activity.java:5133)
10-01 02:02:28.333: E/AndroidRuntime(923):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-01 02:02:28.333: E/AndroidRuntime(923):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-01 02:02:28.333: E/AndroidRuntime(923):  ... 11 more

也试图改变这一行

ListView lv = getListView();

到这个

lv = (ListView) findViewById(android.R.id.list);

但它没有用

我也尝试了一个简单的listview,当我运行它时,项目之间有一个巨大的空间如何解决它?

我想知道手机和平板电脑的实施是否存在差异?

有人能帮帮我吗?谢谢。

1 个答案:

答案 0 :(得分:1)

好吧我认为问题是在xml文件中声明的上下文中。

只需将tools:context=".ViewExs"更改为tools:context=".EditExs"

即可

检查一下。 多数民众赞成......