-1

4 ラッシュの FragmentPagerAdapter を実装し、それぞれに異なるビューのフラグメントをロードします。そのうちの 1 つでは、画像を押すと AsyncTask が実行され、サーバーから一連のデータが取得され、次のように postExecute() メソッドのインテントを通じて新しいクラスが読み込まれます。

  //AsyncTask 
private static class LoadJSON extends AsyncTask<String, Void, String> {

    protected void onPreExecute() {
        mProgressItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        mProgressItem.setVisible(true);
        mProgressItem.setActionView(R.layout.actionbar_indeterminate_progress);
        mProgressItem.expandActionView();
    }

    @Override
    protected String doInBackground(String... params) {                 
        String url = params[0];                
        String data = MetodosJSON.getHttpResponse(url);
        MetodosJSON.parseaJSON2(data, ini.ac);  
        return params[1];               
    }

    protected void onPostExecute(String titulo) {   
        // start new activity           
        Intent i = new Intent(ini.c, PantallaInfo.class);
        i.putExtra("title", titulo);
        i.putExtra("URLser", urlSer);
        ini.startActivity(i);
        mProgressItem.setVisible(false);
    }

}

私はこの機能を 1 つのアクティビティで使用し、完全に機能しました。フラグメントから呼び出しを行うには、このクラス (「ini」) の変数 static を使用して呼び出しを行う必要があり、コード行「ini.startActivity (i)」でエラーが発生します。

FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.Activity.startActivityForResult(Activity.java:3351)
at android.support.v4.app.FragmentActivity.startActivityForresult(FragmentActivity.java:674)
at android.app.Activity.startActivity(Activity.java:3522)
at com.packet.ClassName.AsyncTask.onPostExecute(ClassName.java:432)

誰かが私を助けてくれることを願っています。どうもありがとうございました。

...続けて...私のクラス全体

package com.test;

import ...

public class IniSelCategoria extends SherlockFragmentActivity {

static String urlIni;
static String urlSer;
GridView mGrid;
static Dialog dial;
DisplayMetrics metrics = new DisplayMetrics();
static int width, height;
private static MenuItem mProgressItem;
MyAdapter mAdapter;
ViewPager mViewPager;
static Context c, ac;

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

    c = getBaseContext();
    ac = getApplicationContext();

    // Configuration      
    WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    width = display.getWidth();     
    height = display.getHeight();   

    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    mAdapter = new MyAdapter(getSupportFragmentManager());
    for(int i=0; i<4; i++) {
        Fragment fragment = null;
        switch(i) {
        case 0: 
            fragment = Fragment1.newInstance();
            break;
        case 1:
            fragment = Fragment2.newInstance();
            break;
        case 2:
            fragment = Fragment3.newInstance();
            break;
        case 3:
            fragment = Fragment4.newInstance();
            break;
        }
        mAdapter.addFragment(fragment);
    }
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mAdapter);


    // Intent information
    Bundle recibido = getIntent().getExtras();
    if(recibido != null) {
        urlIni = recibido.getString("URLini");
    }
}

final static IniSelCategoria ini = new IniSelCategoria();

//Options Menu  
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getSupportMenuInflater();
    inflater.inflate(R.menu.iniselcategoria, menu);    
    mProgressItem = menu.findItem(R.id.MenuProgress);
    return true;
}

public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId() == R.id.MenuBuscador) {
        Intent ic3 = new Intent(getBaseContext(), Menu_Buscador.class);
        startActivity(ic3);
        return true;
    }else {
        return super.onOptionsItemSelected(item);
    }
}

//Creation of images
public static class ImageAdapter extends BaseAdapter {
    private Context mContext;
    final AppJSON json = (AppJSON) (IniSelCategoria.ac);

    public ImageAdapter(Context c) {
        mContext = c;
    }     
    public int getCount() {
        return json.json1.GetNumSer();
    }
    public Object getItem(int position) {
        return null;
    }
    public long getItemId(int position) {
        return 0;
    }
 // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView img;       

        if (convertView == null) {
            img = new ImageView(mContext);
            img.setAdjustViewBounds(true);
            img.setScaleType(ImageView.ScaleType.FIT_CENTER);
        } else {
            img = (ImageView) convertView;
        }           

        final String titulo = json.json1.GetTitle(position);
        final int idSer = json.json1.GetIdSer(position);  

       // Configuration images         
        if("Recursos Naturales".equals(titulo)) {               
                img.setImageResource(R.drawable.ic_recursosnaturales);
        }else if("Competitividad".equals(titulo)) {             
                img.setImageResource(R.drawable.ic_competitividad); 
        }else if("Calidad de Vida".equals(titulo)) {            
                img.setImageResource(R.drawable.ic_calidaddevida);
        }else if("Participación".equals(titulo)) {              
                img.setImageResource(R.drawable.ic_participacion);
        }else if("Transporte".equals(titulo)) {         
                img.setImageResource(R.drawable.ic_transporte);             
        }else{
            Toast.makeText(IniSelCategoria.c, "Error", Toast.LENGTH_SHORT).show();
        }           
        img.setOnClickListener(new ImageView.OnClickListener() {
            public void onClick(View v) {   
                urlSer = urlIni + idSer;      
             // get data from the server 
                new CargarJSON(mContext).execute(urlSer, titulo);               
            }
         }); 

        return img;
    }        
}


//AsyncTask 
private static class CargarJSON extends AsyncTask<String, Void, String> {
    Context mContext;
    public CargarJSON(Context context) {
        mContext = context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        mProgressItem.setVisible(true);
        mProgressItem.setActionView(R.layout.actionbar_indeterminate_progress);
        mProgressItem.expandActionView();
    }

    @Override
    protected String doInBackground(String... params) {                 
        String url = params[0];                
        String data = MetodosJSON.getHttpResponse(url);
        MetodosJSON.parseaJSON2(data, IniSelCategoria.ac);  
        return params[1];               
    }

    @Override
    protected void onPostExecute(String titulo) {   
        super.onPostExecute(titulo);
        // start new activity           
        Intent i = new Intent(mContext, PantallaInfo.class);
        i.putExtra("title", titulo);
        i.putExtra("URLser", urlSer);
        ini.startActivity(i);
        mProgressItem.setVisible(false);
    }

}


public static class MyAdapter extends FragmentPagerAdapter {
    private List<Fragment> mFragmentList;

    public MyAdapter(FragmentManager fm) {
        super(fm);
        mFragmentList = new ArrayList<Fragment>();
    }
    public void addFragment(Fragment fragment) {
        mFragmentList.add(fragment);
    }
    @Override
    public int getCount() {
        return mFragmentList.size();
    }
    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }
    @Override
    public CharSequence getPageTitle(int position) {
        return ((CustomFragment) mFragmentList.get(position)).getPageTitle();
    }
}



public static abstract class CustomFragment extends Fragment {
    public abstract String getPageTitle();
}



public static class Fragment1 extends CustomFragment {

    public static Fragment newInstance() {
        Fragment f = new Fragment1();
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        View view = inflater.inflate(R.layout.iniselareas, container, false);

     // Some codes for layout such as findViewById
        final GridView gridServ = (GridView)view.findViewById(R.id.myGrid);            
        if(height > width) {
            gridServ.setNumColumns(1);
        }else {
            gridServ.setNumColumns(2);
        }                 

        gridServ.setAdapter(new ImageAdapter(getActivity()));

        return view;
    }

    @Override
    public String getPageTitle() {
        // return TITLE_FOR_FRAGMENT
        return "ÁREAS TEMÁTICAS";
    }
}

public static class Fragment2 extends CustomFragment {

    ...
}

public static class Fragment3 extends CustomFragment {

    ...
}

public static class Fragment4 extends CustomFragment {

   ...
}


}
4

1 に答える 1

3

cが何かわかりません

  gridServ.setAdapter(new ImageAdapter(c));  //  is c activity context

また

  gridServ.setAdapter(new ImageAdapter(getActivity()));

getActivity()

public final Activity getActivity ()

Added in API level 11
Return the Activity this fragment is currently associated with.

次に、あなたは持っています

  public ImageAdapter(Context c) {
    mContext = c;  
    // you get the activity context here
    // you can use the same 
  } 

アクティビティ コンテキストを asynctask のコンストラクターに渡します。

   new LoadJSON(mContext).execute(url,title); 
  // using mContext initialized in ImageAdapter

次に、asynctask コンストラクターで

   Context mContext;
   public LoadJSON(Context context)
   {
     mContext = context; // get activity context
   }

また

  @Override
  protected void onPreExecute() {
  super.onPreExecute();  

それで

  @Override
  protected void onPostExecute(String titulo) { 
  super.onPostExecute(titulo);

また、mContextを使用してstartActivity

 Intent i = new Intent(mContext, PantallaInfo.class);   
 mContext.startActivity(i);    

startActivityActivity クラスのメソッドです。アクティビティ コンテキストが必要です。

于 2013-10-01T15:52:37.583 に答える