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

格雷厄姆·基尔

我是android的新手,并且一直在使用AndroidHive教程,该教程从远程数据库加载“产品”列表并在列表视图中显示。我正在运行该教程,它非常好,但是我想对其进行修改,以在网格视图而不是列表视图中显示数据,并且不确定如何执行。这是我正在使用的代码。

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

}
}}

<----- XML tt_item ------>假设我不必修改它

 <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" />

<---- XML time_table ----->假设我将不得不更改为标准gridview

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

任何帮助将不胜感激,因为我真的不确定如何解决这个问题。

弗洛

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

  • 更改ListActivityActivity

  • 将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:columnWidthandroid:numColumns就像android:stretchMode控制一样,如何拉伸项目以填充其空间。您可以在“文档”中找到一个简单的教程
希望这可以帮助。


编辑:

始终 需要在findViewByIdmethod内部使用onCreatemethod而不是before用这个:

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

更新:

findViewById()可以称为内的其他方法,比如onAttachonDestroy等- 对不起,我的语法错误)因此,就像上面的代码一样,您可以避免创建var。因此,您只需要这样做(以某种方式更快)

( (GridView) findViewById(R.id.mygrid) ).setAdapter(adapter); // simply

在onPostExecute()内部。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档