【问题标题】:Android: display data from remote database in gridview instead of listview (Convert ListView to GridView)Android:在gridview而不是listview中显示来自远程数据库的数据(将ListView转换为GridView)
【发布时间】:2014-04-04 14:10:55
【问题描述】:

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

}
}}

假设我不必修改这个

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

假设我只需要更改为标准的gridview

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

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

【问题讨论】:

    标签: android database gridview android-listview


    【解决方案1】:

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

    • 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找到一个简单的教程。
    希望这会有所帮助。


    编辑:

    总是需要在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);
       }
    }  
    

    更新:

    findViewById() 可以在 onAttachonDestroy 等其他方法中调用 - (抱歉我的语法错误)。因此,正如您上面的代码,您可以避免创建一个 var。所以你只需要这样做(在某种程度上更快)

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

    在 onPostExecute() 内部。

    【讨论】:

    • 感谢您的回复,不幸的是,这些修改已接近尾声。
    • 您能否将您的代码更新到您的问题中并添加您的 LogCat。我会尽力帮助你解决你的错误。 - 我更新了我的答案,你应该在执行后创建一个初始化变量来设置你的适配器,这样可以避免出现 NullPointerException 错误。
    • 非常感谢@Fllo 的帮助,我用你给我的代码取消了我的问题,现在它工作得很好。我真的很感激。
    • @GrahamKill 很高兴能提供帮助,但最好使用变量,正如您在我的更新中看到的那样。这样可以避免您一次又一次地重用 findViewById 方法。
    • 好的,我明白了。我会尝试再次修改它以更好地工作。再次感谢。
    猜你喜欢
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-14
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多