2014-10-07 36 views
-2

我想要我的應用程序從一個活動轉換成片段 我的應用程序的JSON的有來自互聯網的ListView拋出該負載JSON 我搜索的例子或有關JSON文檔中的片段 工作或轉換活動的片段細節,我無法找到任何有用的材料例如用片段

所以任何幫助,請:)

這裏是我想從活動轉換器它片段爲例

public class MainActivity extends Activity { 








    /////////////////////////// 


    private DrawerLayout mDrawerLayout; 
    private ListView mDrawerList; 
    private ActionBarDrawerToggle mDrawerToggle; 

    // nav drawer title 
    private CharSequence mDrawerTitle; 

    // used to store app title 
    private CharSequence mTitle; 

    // slide menu items 
    private String[] navMenuTitles; 
    private TypedArray navMenuIcons; 

    private ArrayList<NavDrawerItem> navDrawerItems; 
    private NavDrawerListAdapter listadapter; 

    ///////////////////////////////// 





    int counter = 0; 

    // Log tag 
    private static final String TAG = MainActivity.class.getSimpleName(); 

    // Movies json url 
    private static final String url = "http://api.androidhive.info/json/movies.json"; 
    private ProgressDialog pDialog; 
    private List<Movie> movieList = new ArrayList<Movie>(); 
    private ListView listView; 
    private CustomListAdapter adapter; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 





     ///////////////////////////////////// 



     mTitle = mDrawerTitle = getTitle(); 

     // load slide menu items 
     navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items); 

     // nav drawer icons from resources 
     navMenuIcons = getResources() 
       .obtainTypedArray(R.array.nav_drawer_icons); 

     mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); 
     mDrawerList = (ListView) findViewById(R.id.list_slidermenu); 

     navDrawerItems = new ArrayList<NavDrawerItem>(); 

     // adding nav drawer items to array 
     // Home 
     navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1))); 
     // Find People 
     navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1))); 
     // Photos 
     navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1))); 
     // Communities, Will add a counter here 
     navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22")); 
     // Pages 
     navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1))); 
     // What's hot, We will add a counter here 
     navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+")); 


     // Recycle the typed array 
     navMenuIcons.recycle(); 

     mDrawerList.setOnItemClickListener(new SlideMenuClickListener()); 

     // setting the nav drawer list adapter 
     listadapter = new NavDrawerListAdapter(getApplicationContext(), 
       navDrawerItems); 
     mDrawerList.setAdapter(listadapter); 

     // enabling action bar app icon and behaving it as toggle button 
     getActionBar().setDisplayHomeAsUpEnabled(true); 
     getActionBar().setHomeButtonEnabled(true); 

     mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, 
       R.drawable.ic_drawer, //nav menu toggle icon 
       R.string.app_name, // nav drawer open - description for accessibility 
       R.string.app_name // nav drawer close - description for accessibility 
     ) { 
      public void onDrawerClosed(View view) { 
       getActionBar().setTitle(mTitle); 
       // calling onPrepareOptionsMenu() to show action bar icons 
       invalidateOptionsMenu(); 
      } 

      public void onDrawerOpened(View drawerView) { 
       getActionBar().setTitle(mDrawerTitle); 
       // calling onPrepareOptionsMenu() to hide action bar icons 
       invalidateOptionsMenu(); 
      } 
     }; 
     mDrawerLayout.setDrawerListener(mDrawerToggle); 

     if (savedInstanceState == null) { 
      // on first time display view for first nav item 
      displayView(0); 
     } 


     /////////////////////////////////////// 









     listView = (ListView) findViewById(R.id.list); 
     adapter = new CustomListAdapter(this, movieList); 
     listView.setAdapter(adapter); 
     listView.setOnScrollListener(new EndlessScrollListener() { 

      @Override 
      public void onLoadMore(int page, int totalItemsCount) { 
       // TODO Auto-generated method stub 
       // new Loadmore().execute(); 
       loadList(counter); 
      } 
     }); 
     loadList(counter); 

    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

    public void loadList(int i) 
    { 
     pDialog = new ProgressDialog(this); 
     // Showing progress dialog before making http request 
     pDialog.setMessage("Loading..."); 
     pDialog.show(); 

     // changing action bar color 
     getActionBar().setBackgroundDrawable(
       new ColorDrawable(Color.parseColor("#1b1b1b"))); 

     // Creating volley request obj 
     JsonArrayRequest movieReq = new JsonArrayRequest(url, 
       new Response.Listener<JSONArray>() { 
        @Override 
        public void onResponse(JSONArray response) { 
         Log.d(TAG, response.toString()); 
         hidePDialog(); 

         int subcounter = counter +3; 
         // Parsing json 
         for (int i = counter; i < (subcounter); i++) { 
          try { 

           JSONObject obj = response.getJSONObject(i); 
           Movie movie = new Movie(); 
           movie.setTitle(obj.getString("title")); 
           movie.setThumbnailUrl(obj.getString("image")); 
           movie.setRating(((Number) obj.get("rating")) 
             .doubleValue()); 
           movie.setYear(obj.getInt("releaseYear")); 

           // Genre is json array 
           JSONArray genreArry = obj.getJSONArray("genre"); 
           ArrayList<String> genre = new ArrayList<String>(); 
           for (int j = 0; j < genreArry.length(); j++) { 
            genre.add((String) genreArry.get(j)); 
           } 
           movie.setGenre(genre); 

           // adding movie to movies array 
           movieList.add(movie); 

          } catch (JSONException e) { 
           e.printStackTrace(); 
          } 

         } 
         counter = counter + 3 ; 
         // notifying list adapter about data changes 
         // so that it renders the list view with updated data 
         adapter.notifyDataSetChanged(); 
        } 
       }, new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 
         VolleyLog.d(TAG, "Error: " + error.getMessage()); 
         hidePDialog(); 

        } 
       }); 

     // Adding request to request queue 
     AppController.getInstance().addToRequestQueue(movieReq); 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     hidePDialog(); 
    } 

    private void hidePDialog() { 
     if (pDialog != null) { 
      pDialog.dismiss(); 
      pDialog = null; 
     } 
    } 










    private void displayView(int position) { 
     // update the main content by replacing fragments 
     Fragment fragment = null; 
     switch (position) { 
     case 0: 

      break; 
     case 1: 
      Intent i = new Intent(MainActivity.this,MainActivity.class); 


       startActivity(i); 
       finish(); 
      break; 
     case 2: 

      break; 
     case 3: 

      break; 
     case 4: 

      break; 
     case 5: 

      break; 

     default: 
      break; 
     } 



      // update selected item and title, then close the drawer 
      mDrawerList.setItemChecked(position, true); 
      mDrawerList.setSelection(position); 
      setTitle(navMenuTitles[position]); 
      mDrawerLayout.closeDrawer(mDrawerList); 


    } 

    @Override 
    public void setTitle(CharSequence title) { 
     mTitle = title; 
     getActionBar().setTitle(mTitle); 
    } 

    /** 
    * When using the ActionBarDrawerToggle, you must call it during 
    * onPostCreate() and onConfigurationChanged()... 
    */ 

    @Override 
    protected void onPostCreate(Bundle savedInstanceState) { 
     super.onPostCreate(savedInstanceState); 
     // Sync the toggle state after onRestoreInstanceState has occurred. 
     mDrawerToggle.syncState(); 
    } 

    @Override 
    public void onConfigurationChanged(Configuration newConfig) { 
     super.onConfigurationChanged(newConfig); 
     // Pass any configuration change to the drawer toggls 
     mDrawerToggle.onConfigurationChanged(newConfig); 
    } 

    private void forceRTLIfSupported() 
    { 
     if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){ 
      getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL); 
     } 
    } 





    private class SlideMenuClickListener implements 
    ListView.OnItemClickListener { 
@Override 
public void onItemClick(AdapterView<?> parent, View view, int position, 
     long id) { 
    // display view for selected nav drawer item 
    displayView(position); 
} 
} 




} 

public class AppController extends Application { 

    public static final String TAG = AppController.class.getSimpleName(); 

    private RequestQueue mRequestQueue; 
    private ImageLoader mImageLoader; 

    private static AppController mInstance; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     mInstance = this; 
    } 

    public static synchronized AppController getInstance() { 
     return mInstance; 
    } 

    public RequestQueue getRequestQueue() { 
     if (mRequestQueue == null) { 
      mRequestQueue = Volley.newRequestQueue(getApplicationContext()); 
     } 

     return mRequestQueue; 
    } 

    public ImageLoader getImageLoader() { 
     getRequestQueue(); 
     if (mImageLoader == null) { 
      mImageLoader = new ImageLoader(this.mRequestQueue, 
        new LruBitmapCache()); 
     } 
     return this.mImageLoader; 
    } 

    public <T> void addToRequestQueue(Request<T> req, String tag) { 
     // set the default tag if tag is empty 
     req.setTag(TextUtils.isEmpty(tag) ? TAG : tag); 
     getRequestQueue().add(req); 
    } 

    public <T> void addToRequestQueue(Request<T> req) { 
     req.setTag(TAG); 
     getRequestQueue().add(req); 
    } 

    public void cancelPendingRequests(Object tag) { 
     if (mRequestQueue != null) { 
      mRequestQueue.cancelAll(tag); 
     } 
    } 
} 

========================================== =======================

public class LruBitmapCache extends LruCache<String, Bitmap> implements 
     ImageCache { 
    public static int getDefaultLruCacheSize() { 
     final int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024); 
     final int cacheSize = maxMemory/8; 

     return cacheSize; 
    } 

    public LruBitmapCache() { 
     this(getDefaultLruCacheSize()); 
    } 

    public LruBitmapCache(int sizeInKiloBytes) { 
     super(sizeInKiloBytes); 
    } 

    @Override 
    protected int sizeOf(String key, Bitmap value) { 
     return value.getRowBytes() * value.getHeight()/1024; 
    } 

    @Override 
    public Bitmap getBitmap(String url) { 
     return get(url); 
    } 

    @Override 
    public void putBitmap(String url, Bitmap bitmap) { 
     put(url, bitmap); 
    } 
} 

我不知道很多片段的所以我完全失去了每次我嘗試更改代碼,我得到很多錯誤

+0

發佈您的代碼.. – Brendon 2014-10-07 09:54:31

+0

http://www.learn2crack.com/2014/05/android-working-with-fragments.html – 2014-10-07 09:54:47

+0

使用異步任務,你也可以從碎片中下載你的json。爲了清楚理解,請發佈您的代碼。 – LvN 2014-10-07 09:57:11

回答

1

您無法將活動轉換爲片段。片段包含在活動中。您可以使用片段管理器添加/替換片段。

你可以做什麼來實現你所需要的,它從你的網站加載json。將其轉換爲java對象並將它們放入一個列表中。爲這個java對象編寫一個適配器。

如果你是從android開發開始的,我會建議你先在一個簡單的活動中完成它,然後將你的代碼移動到片段中,如果你需要的話。

關於資源需要

的AsyncTask加載數據wihtout bocking UI線程 http://developer.android.com/reference/android/os/AsyncTask.html

如何解析JSON在Java

http://www.tutorialspoint.com/json/json_java_example.htm

Android的列表視圖和適配器顯示您的清單

http://developer.android.com/guide/topics/ui/layout/listview.html http://developer.android.com/reference/android/widget/Adapter.html

1

首先,你必須讓它擴展片段實現等等等等 JSON分析器正在與這兩個片段和活動,當轉換到活動片段你必須玩的,

this -> getActivity() 

this -> getApplicationContext(); 

檢查例子@http://www.androidhive.info/

+0

儘管這個鏈接可能回答這個問題,但最好在這裏包含答案的重要部分,並提供供參考的鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 – arco444 2014-10-07 10:27:32

+0

您提供的鏈接是隨時間變化的文章集合。最好鏈接到包含該示例的實際文章(並且包括它的基本(示例)部分,如@ arco444已經提到的!) – Veger 2014-10-07 10:49:52

+0

其實這是我的第一個答案,我對此沒有太多想法,對不起不方便。 – 2014-10-07 10:58:54