2014-04-04 52 views
-1

我是剛接觸Android並且一直在使用AndroidHive教程,該教程從遠程數據庫加載「產品」列表並顯示它在一個列表視圖。我有教程運行,這是非常好的,但我想修改它顯示在gridview而不是一個列表視圖的數據,我不知道如何。這是我正在使用的代碼。Android:在GridView中顯示來自遠程數據庫的數據而不是ListView(將ListView轉換爲GridView)

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

任何幫助將是非常讚賞,因爲我真的不知道如何去解決這個。

回答

0

很簡單。你必須做一些改變,如下:

  • 變化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:columnWidth及其與android:numColumns號。由於android:stretchMode用於控制物品如何被拉伸以填充其空間。你可以在Documentation找到一個簡單的教程。
希望這會有所幫助。


編輯:

總是 需要使用findViewById方法內onCreate方法不之前。使用此:

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

UPDATE:

findViewById()可以在裏面其他的方法被稱爲像onAttachonDestroy,等等 - (對不起我的語法錯誤)。因此,作爲上面的代碼,你可以避免創建一個var。所以,你必須要做到這一點(在某種程度上更快)

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

內onPostExecute()。

+0

感謝您的迴應,不幸的是得到了一個接近這些修改的力量。 – GrahamKill

+0

您是否可以將您的代碼更新到您的問題中,並且請添加您的LogCat。我會盡力幫助你解決你的錯誤。 - 我更新了我的答案,您應該在postexecute之後創建一個init變量來設置您的適配器,這樣可以避免發生NullPointerException錯誤。 – Fllo

+0

@GrahamKill我更新了我的答案。 – Fllo