2014-09-26 86 views
0

我有一個從我的數據庫retrives數據,並使用簡單的適配器從簡單的列表適配器來定製陣列適配器

public class ViewExs 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; 

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

    // 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) { 
      Intent i = new Intent(getApplicationContext(), EditProductActivity.class); 
      startActivity(i); 

     /* // getting values from selected ListItem 
      String pid = ((TextView) view.findViewById(R.id.pid)).getText() 
        .toString(); 

      // Starting new intent 
      Intent in = new Intent(getApplicationContext(), 
        EditProductActivity.class); 
      // sending pid to next activity 
      in.putExtra(TAG_PID, pid); 

      // 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(ViewExs.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) { 
     // Building Parameters 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     // 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(
         ViewExs.this, productsList, 
         R.layout.item_list_3, new String[] {TAG_NAME}, 
         new int[] { R.id.pid}); 
       // updating listview 
       setListAdapter(adapter); 
      } 
     }); 

    } 

} 
} 

我想使用自定義適配器,而不是簡單的適配器其顯示在列表視圖類。 。這裏是我的自定義適配器

public class MySimpleArrayAdapter extends ArrayAdapter<String> { 
    private final Context context; 
    private final String[] values; 
    TextView textView; 

    public MySimpleArrayAdapter(Context context, String[] values) { 
    super(context, R.layout.item_list_3, values); 
    this.context = context; 
    this.values = values; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
    LayoutInflater inflater = (LayoutInflater) context 
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View rowView = inflater.inflate(R.layout.item_list_3, parent, false); 

    final TextView textView = (TextView) rowView.findViewById(R.id.pid); 
textView.setText(values[position]); 

return rowView; 
    } 
    } 

我如何做個代碼

ListAdapter adapter = new SimpleAdapter(
         ViewExs.this, productsList, 
         R.layout.item_list_3, new String[] {TAG_NAME}, 
         new int[] { R.id.pid}); 
       // updating listview 
       setListAdapter(adapter); 

這部分e自定義適配器?

有人可以幫忙嗎?

+0

'MySimpleArrayAdapter適配器=新MySimpleArrayAdapter(ViewExs.this,新的String [] {TAG_NAME});' – 2014-09-26 10:58:29

+0

@PedroOliveira但這不會從數據庫retrive .. – Lamawy 2014-09-27 04:46:32

回答

0

只需使用你的方法MySimpleArrayAdapter,並設置適配器 -

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 
       * */ 
       MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(ViewExs.this, 
       new String[] {TAG_NAME}); 

       // updating listview 
       setListAdapter(adapter); 
      } 
     }); 

    } 
+0

做我改變了適配器的東西?因爲我在運行時遇到錯誤 – Lamawy 2014-09-26 14:47:22

+0

不是錯誤,但它不會從數據庫中檢索 – Lamawy 2014-09-27 04:47:23

0

假設你的價值觀的陣列中的String []值,然後

MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(
        ViewExs.this,values); 
    setListAdapter(adapter); 
+0

我需要更改適配器中的某些內容嗎?因爲我運行時出錯了 – Lamawy 2014-09-27 04:28:52

+0

你得到了什麼錯誤? – Beena 2014-09-27 04:32:10

+0

不抱歉,它不是一個錯誤,但它不會從數據庫中檢索它只會打印ID_exercise – Lamawy 2014-09-27 04:35:35

0

您好我使用了自定義陣列適配器像下面的一個,這只是一個例子。但我希望它有幫助。它顯示使用ArrayList從它顯示的片段發送給它的數據。

public class MovieAdapter extends ArrayAdapter<Movie> { 
    private Context context; 
    private List<Movie> movies; 

    public MovieAdapter(Context context, List<Movie> movies) { 
     super(context, R.layout.movie_layout, movies); 
     this.context = context; 
     this.movies = movies; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     View movieView = convertView; 

     if (movieView == null) { 
      LayoutInflater inflater = (LayoutInflater) context 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      movieView = inflater.inflate(R.layout.movie_layout, parent, false); 
     } 
     movieView.setTag(movies.get(position)); 
     TextView txtTitle = (TextView) movieView.findViewById(R.id.txtTitle); 
     TextView txtDate = (TextView) movieView.findViewById(R.id.txtDate); 
     RatingBar ratingBar = (RatingBar) movieView 
       .findViewById(R.id.ratingBar); 
     txtTitle.setText(movies.get(position).MovieTitle); 
     txtDate.setText("Date Viewed: " + movies.get(position).dateViewed); 
     ratingBar.setIsIndicator(true); 
     ratingBar.setNumStars(movies.get(position).rating); 
     ratingBar.setRating(movies.get(position).rating); 
     return movieView; 
    } 
} 

片段

public class MyListFragment extends Fragment { 

    Movie movie; 
    MovieAdapter adapter; 
    MovieSelectedListener callBack; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.list_fragment, container, false); 

     ListView movieList = (ListView) view.findViewById(R.id.movieList); 

     movieList.setOnItemClickListener(new OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> parent, View view, 
        int position, long id) { 
       // TODO Auto-generated method stub 
       TextView movie = (TextView) view.findViewById(R.id.txtTitle); 
       String title = movie.getText().toString(); 
       callBack.onMovieSelected(title); 
      } 
     }); 

     if (getArguments() != null) 
      movie = (Movie) getArguments().getSerializable("Movie"); 
     Log.v("PASSED", "Got here"); 
     adapter = new MovieAdapter(getActivity(), movie.movies); 
     movieList.setAdapter(adapter); 
     movieList.setLongClickable(true); 
     movieList.setOnItemLongClickListener(new OnItemLongClickListener() { 

      @Override 
      public boolean onItemLongClick(AdapterView<?> parent, 
        final View view, int position, long id) { 
       // TODO Auto-generated method stub 
       AlertDialog.Builder dialog = new AlertDialog.Builder(
         getActivity()); 
       dialog.setMessage("Are you sure you want to delete this movie?"); 
       dialog.setTitle("Alert Message"); 
       dialog.setCancelable(false); 
       dialog.setPositiveButton("Yes", 
         new DialogInterface.OnClickListener() { 

          public void onClick(DialogInterface dialog, 
            int which) { 
           // TODO Auto-generated method stub 
           TextView movie = (TextView) view 
             .findViewById(R.id.txtTitle); 
           String title = movie.getText().toString(); 
           callBack.onDeleteSelected(title, adapter); 

          } 
         }); 
       dialog.setNegativeButton("No", 
         new DialogInterface.OnClickListener() { 

          public void onClick(DialogInterface dialog, 
            int which) { 
           // TODO Auto-generated method stub 
          } 
         }); 
       dialog.show(); 
       return false; 
      } 
     }); 
     return view; 
    } 

    public interface MovieSelectedListener { 
     public void onMovieSelected(String movie); 

     public void onDeleteSelected(String movie, MovieAdapter adapter); 
    } 

    @Override 
    public void onAttach(Activity activity) { 
     super.onAttach(activity); 
     ; 
     try { 
      callBack = (MovieSelectedListener) activity; 
     } catch (ClassCastException e) { 
      throw new ClassCastException(activity.toString() 
        + " must implement MovieSelectedListener"); 
     } 
    } 

    public void sortTitle() { 

     adapter.sort(new Comparator<Movie>() { 
      public int compare(Movie lhs, Movie rhs) { 
       return lhs.MovieTitle.compareTo(rhs.MovieTitle); 
      } 
     }); 
     adapter.notifyDataSetChanged(); 
    } 

    public void sortDateViewed() { 

     adapter.sort(new Comparator<Movie>() { 
      public int compare(Movie lhs, Movie rhs) { 
       return lhs.dateViewed.compareTo(rhs.dateViewed); 
      } 
     }); 
     adapter.notifyDataSetChanged(); 
    } 

    public void sortRating() { 

     adapter.sort(new Comparator<Movie>() { 
      public int compare(Movie lhs, Movie rhs) { 
       return ((Integer) lhs.rating).compareTo(rhs.rating); 
      } 
     }); 
     adapter.notifyDataSetChanged(); 
    } 
}