Android:在gridview而不是listview中显示来自远程数据库的数据(将ListView转换为GridView)

时间:2014-04-04 14:10:56

标签: android database gridview android-listview

我是Android新手,并且一直在使用AndroidHive教程,该教程加载了一系列产品"从远程数据库中将其显示在列表视图中。我有教程运行,它非常好,但我想修改它在gridview而不是listview中显示数据,我不知道如何。这是我正在使用的代码。

public class TimeTableActivity extends Activity {

// Progress Dialog
private ProgressDialog pDialog;

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

ArrayList<HashMap<String, String>> modulesList;

// url to get all modules list
private static String url_all_modules = "  http://<MyIPAddress>/timetable/get_all_modules.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_MODULES = "modules";
private static final String TAG_MODID = "modid";
private static final String TAG_MODULE_NAME = "module_name";
private static final String TAG_DAY = "day";


//   modules JSONArray
JSONArray modules = null;

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


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

// Loading modules in Background Thread
new LoadAllmodules().execute();

GridView grid = (GridView) findViewById(R.id.mygrid);

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


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





        // Starting new intent
        //Intent in = new Intent(getApplicationContext(),
        //  TimeTableActivity.class);
        // sending modid to next activity
        //in.putExtra(TAG_MODID, modid);

        // 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 LoadAllmodules extends AsyncTask<String, String, String> {

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

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

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

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

        if (success == 1) {
            // modules found
            // Getting Array of modules
            modules = json.getJSONArray(TAG_MODULES);

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

                // Storing each json item in variable
                String id = c.getString(TAG_MODID);
                String day = c.getString(TAG_DAY);
                String name = c.getString(TAG_MODULE_NAME);



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

                // adding each child node to HashMap key => value
                map.put(TAG_MODID, id);
                map.put(TAG_DAY, day);
                map.put(TAG_MODULE_NAME, name);


                // adding HashList to ArrayList
                modulesList.add(map);
            }
        } else {

            Toast.makeText(getApplicationContext(), "Time Table cannot be displayed right now",
                       Toast.LENGTH_LONG).show();
            // no modules 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
 * **/
@Override
protected void onPostExecute(String file_url) {
    // dismiss the dialog after getting all modules
    pDialog.dismiss();
    // updating UI from Background Thread
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            /**
             * Updating parsed JSON data into ListView
             * */

 GridView grid = (GridView) findViewById(R.id.mygrid);

            ListAdapter adapter = new SimpleAdapter(
                    TimeTableActivity.this, modulesList,
                    R.layout.tt_item, new String[] {     TAG_MODID, TAG_DAY,
                            TAG_MODULE_NAME},
                    new int[] { R.id.modid, R.id.day,     R.id.name});

            // updating listview
            grid.setAdapter(adapter);
        }
    });

}
}}

&lt; ----- XML tt_item ------&gt;假设我不必修改此

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


<!-- Name Label -->
<TextView
 android:id="@+id/day"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:paddingTop="6dip"
 android:paddingLeft="6dip"
 android:textSize="17sp"
 android:textStyle="bold" />

 <TextView
 android:id="@+id/name"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:paddingTop="6dip"
 android:paddingLeft="6dip"
 android:textSize="17sp"
 android:textStyle="bold" />

&lt; ---- XML time_table -----&gt;假设我只需要更改为标准gridview

 <GridView
 android:id="@+id/mygrid"
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent"
 android:numColumns="2"
 android:stretchMode="columnWidth" />  

任何帮助都会非常感激,因为我真的不知道如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

这很简单。您必须进行一些更改,如下所示:

  • ListActivity更改为Activity

  • 将GridView变量初始化为GridView grid;

  • ListView lv = getListView();应为grid = (GridView) findViewById(R.id.mygrid)
    因此lv.setOnItemClickListener(...)应为grid.setOnItemClickListener(...)

  • 然后,此setListAdapter(adapter);变为grid.setAdapter(adapter)

  • 最后,你的布局是:

    <GridView
         android:id="@+id/mygrid"
         android:layout_width="fill_parent" 
         android:layout_height="fill_parent"
         android:numColumns="2"
         android:stretchMode="columnWidth" />  
    

您可以选择android:columnWidth列的宽度和android:numColumns的数字。由于android:stretchMode用于控制物品如何拉伸以填充其空间。您可以在Documentation找到一个简单的教程 希望这会有所帮助。


编辑:

总是需要在{/ 1}}方法中使用findViewById方法而不是之前的。使用此:

onCreate

更新:

findViewById()可以在其他方法中调用,如public class TimeTableActivity extends Activity { // init a variable GridView grid; // Then, in onCreate method find its id @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.time_table); // find the view grid = (GridView) findViewById(R.id.mygrid); } // ... // Finally, in onPostExecute method, reuse the SAME variable as above @Override protected void onPostExecute(String file_url) { // ... // reuse *grid* grid.setAdapter(adapter); } } onAttach等 - (抱歉我的语法错误)。因此,作为上面的代码,您可以避免创建var。所以你只需要这样做(在某种程度上更快)

onDestroy

在onPostExecute()中。