片段内的Viewpager,网络IO访问主UI线程错误

时间:2013-12-16 01:10:12

标签: android json android-fragments android-asynctask android-viewpager

我正在尝试将viewpager放在我的项目中的一个片段中。最初我使用asynctask为diff项目上的图像加载json解析。

当我尝试将json项目与我的片段项目组合时,我删除了asyctask,因为我不知道如何一起实现它们。

下面是我的代码和错误日志,问题这里是网络IO试​​图访问主UI线程,但没有asynctask我不知道如何解决它

非常感谢任何帮助。

MainActivity

public class MainActivity extends FragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);  
    super.onCreate(savedInstanceState);     
    setContentView(R.layout.main);


    FragmentTabHost tabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
    tabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
    //1
    tabHost.addTab(tabHost.newTabSpec("Highlight").setIndicator("Highlight"), 
                  AppleFragment.class, null);
         ...
    //4
    tabHost.addTab(tabHost.newTabSpec("Gallery").setIndicator("Gallery"), 
                  GalleryFragment.class,  null);

GalleryFragment

public class GalleryFragment extends Fragment{
    private ViewPager mPager;
    private PagerAdapter mPagerAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_pager, container,false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPager = (ViewPager) view.findViewById(R.id.pager);
        mPagerAdapter = new CustomPagerAdapter(getChildFragmentManager());
        mPager.setAdapter(mPagerAdapter);
        mPager.setCurrentItem(0);
    }

ViewPagerPageFragment

public class ViewPagerPageFragment extends Fragment{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_page,container,false);
}

    // url to make request
    private static String url = "http://vina.harvestcamasu.com/vina/xml/image.json";

    // JSON Node names
    static String TAG_IMAGE     = "Image";
    static String TAG_PICURL    = "PicURL";
    private String[] images = new String[13];
    ProgressDialog mProgressDialog;
    public Drawable d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13;

    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.findViewById(R.id.imageView1);




                try {
                    // Do something...
                    Thread.sleep(5000);
                    JSONParser jParser = new JSONParser();
                    jParser.getJSONFromUrl(url);

                    // get Gallery JSONObject
                    JSONObject json = jParser.getJSONFromUrl(url);
                    // get Artist JSONObject
                    JSONObject json_gallery=json.getJSONObject("Gallery");
                    // get Image JSONArray
                    JSONObject json_artist=json_gallery.getJSONObject("Artist");


                    //getting array from image
                    JSONArray Image = null;
                    try {
                        Image = json_artist.getJSONArray(TAG_IMAGE);
                        for (int i = 0; i < Image.length(); i++) {

                            JSONObject m    = Image.getJSONObject(i);
                            images[i]       = m.getString("PicURL");


                        }
                        InputStream is1 = (InputStream) new URL(images[0]).getContent();
                        d1 = Drawable.createFromStream(is1, "src name");
                        .
                        .
                        .   
                        InputStream is13= (InputStream) new URL(images[12]).getContent();
                        d13= Drawable.createFromStream(is13, "src name");


                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }


                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return ;

            }



    }

CustomPagerAdapter

public class CustomPagerAdapter extends FragmentStatePagerAdapter {
public CustomPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int position) {
    return new ViewPagerPageFragment();
}


private Drawable d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13;


public void MyPagerAdapter( Drawable draw1, Drawable draw2,Drawable draw3,Drawable draw4,Drawable draw5,
        Drawable draw6,Drawable draw7,Drawable draw8,Drawable draw9,Drawable draw10,Drawable draw11,
        Drawable draw12,Drawable draw13){

    d1 = draw1;
    .
    .               
    d13= draw13;


}

public int getCount() {

    return 13;
}
public Object instantiateItem(View collection, int position) {
    LayoutInflater inflater = (LayoutInflater) collection.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    int resId = R.layout.first_page;
    View view = inflater.inflate(resId, null);

    ImageView image1 = (ImageView)view.findViewById(R.id.imageView1);

    switch (position) {
    case 0:
         image1.setImageDrawable(d1);
        break;
    .
    .
    case 12:
         image1.setImageDrawable(d13);
           break;
    }

    ((ViewPager) collection).addView(view, 0);
    return view;
}

public void destroyItem(View arg0, int arg1, Object arg2) {
    ((ViewPager) arg0).removeView((View) arg2);
}

public boolean isViewFromObject(View arg0, Object arg1) {
    return arg0 == ((View) arg1);
}

public Parcelable saveState() {
    return null;
}
}

错误记录

12-12 14:25:08.929: E/AndroidRuntime(9185): FATAL EXCEPTION: main
12-12 14:25:08.929: E/AndroidRuntime(9185): android.os.NetworkOnMainThreadException
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at com.tonycube.fragmenttabdemo.JSONParser.getJSONFromUrl(JSONParser.java:39)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at com.tonycube.fragmenttabdemo.ViewPagerPageFragment.onViewCreated(ViewPagerPageFragment.java:56)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:925)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.support.v4.view.ViewPager.populate(ViewPager.java:1064)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.support.v4.view.ViewPager.populate(ViewPager.java:911)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1432)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.view.View.measure(View.java:12892)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:594)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:376)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.view.View.measure(View.java:12892)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.view.View.measure(View.java:12892)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.view.View.measure(View.java:12892)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:812)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:553)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.view.View.measure(View.java:12892)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.view.View.measure(View.java:12892)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.view.View.measure(View.java:12892)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1375)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:660)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:553)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.view.View.measure(View.java:12892)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2257)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.view.View.measure(View.java:12892)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1240)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2628)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.os.Looper.loop(Looper.java:137)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at android.app.ActivityThread.main(ActivityThread.java:4512)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at java.lang.reflect.Method.invokeNative(Native Method)
12-12 14:25:08.929: E/AndroidRuntime(9185):     at java.lang.reflect.M

1 个答案:

答案 0 :(得分:0)

你应该在线程或异步

中使用下面的代码
try {
                    // Do something...
                    Thread.sleep(5000);
                    JSONParser jParser = new JSONParser();
                    jParser.getJSONFromUrl(url);

                    // get Gallery JSONObject
                    JSONObject json = jParser.getJSONFromUrl(url);
                    // get Artist JSONObject
                    JSONObject json_gallery=json.getJSONObject("Gallery");
                    // get Image JSONArray
                    JSONObject json_artist=json_gallery.getJSONObject("Artist");


                    //getting array from image
                    JSONArray Image = null;
                    try {
                        Image = json_artist.getJSONArray(TAG_IMAGE);
                        for (int i = 0; i < Image.length(); i++) {

                            JSONObject m    = Image.getJSONObject(i);
                            images[i]       = m.getString("PicURL");


                        }
                        InputStream is1 = (InputStream) new URL(images[0]).getContent();
                        d1 = Drawable.createFromStream(is1, "src name");
                        .
                        .
                        .   
                        InputStream is13= (InputStream) new URL(images[12]).getContent();
                        d13= Drawable.createFromStream(is13, "src name");


                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }


                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return ;

            }