Question

This is my 3rd app, and I think I'm too ambitious to do this. An app that shows me a listview with some names and when clicked change an imageview, this image is retrieve from URL. Also, I want to screen slide and it can show me more of "template"s I've just described. Here is where I had most of the problems.

Solved {

My logcat says:

05-13 23:20:38.516: E/AndroidRuntime(687): java.lang.RuntimeException:
Unable to instantiate activity ComponentInfo{com.example.test2/
com.example.test2.ScreenSlideActivity}: java.lang.NullPointerException

}

New problem

On click on listviewit stops showing:

05-13 23:51:46.751: E/AndroidRuntime(782): java.lang.RuntimeException: An error occured while executing doInBackground()
05-13 23:51:46.751: E/AndroidRuntime(782):  at android.os.AsyncTask$3.done(AsyncTask.java:299)

Main Activity

public class ScreenSlideActivity extends ActionBarActivity {


SectionsPagerAdapter mSectionsPagerAdapter;

ViewPager mViewPager;

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

    mSectionsPagerAdapter = new SectionsPagerAdapter(
            getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return PlaceholderFragment.newInstance(position);
    }

    @Override
    public int getCount() {
        return 6;
    }

}
public static class PlaceholderFragment extends Fragment {
    private static final String ARG_SECTION_NUMBER = "section_number";

    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args); 
        return fragment;
    }

    public PlaceholderFragment() {
    }

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

        String[] ponies = getResources().getStringArray(R.array.ponies);
        String[] poniesurl=getResources().getStringArray(R.array.poniesimg);
        final ArrayList<String> listurl = new ArrayList<String>();
        ListView listview = (ListView) rootView.findViewById(R.id.lista);
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < ponies.length; ++i) {
              list.add(ponies[i]);
              listurl.add(poniesurl[i]);
            }
        ArrayAdapter<String> arrayAdapter = 
                new ArrayAdapter<>(getActivity().getApplicationContext()
                        ,android.R.layout.simple_list_item_1,list);
        listview.setAdapter(arrayAdapter);
        listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                String selectedPonyURL=listurl.get(position);
                new ScreenSlideActivity().new DownloadImagesTask().execute(selectedPonyURL);
            }

        });

        return rootView;
    }
}
class DownloadImagesTask extends AsyncTask<String, Void, Bitmap> {


    protected Bitmap doInBackground(String... data) {
        String thumb = data[0];
        Bitmap bitmap = null;
        try {
            Log.d("TEST", "do in background");
            bitmap = BitmapFactory
                    .decodeStream((InputStream) new URL(thumb).getContent());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap img) {
        Log.d("TEST", "post execute");
        ImageView mChart = (ImageView) findViewById(R.id.imageView1);
        mChart.setImageBitmap(img);
    }}

}

My Layouts

activiy_screen_slide.xml

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.test2.ScreenSlideActivity" />

fragment_screen_slide.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
 >

<ImageView
    android:id="@+id/imageView1"
    android:paddingTop="10dp"
    android:layout_width="wrap_content"
    android:layout_height="200dip"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:src="@drawable/ic_launcher" />



<ListView
    android:id="@+id/lista"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/button1"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/imageView1" >

</ListView>

</RelativeLayout>

and my list

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="ponies">
        <item>Rainbow Dash</item>
        <item>Apple Jack</item>
        <item>Rarity</item>
        <item>Pinkie Pie</item>
        <item>Twilight Sparkle</item>
        <item>Fluttershy</item>
    </string-array>
    <array name="poniesimg">
        <item>http://fc08.deviantart.net/fs71/f/2012/087/d/e/rainbow_dash_icon_request_by_megasuperheavy-d4u76ht.png</item>
        <item>https://www.fimfiction-static.net/images/avatars/28886_256.jpg?1336013578</item>
        <item>http://www.fimfiction-static.net/images/avatars/139363_256.jpg?1382473406</item>
        <item>https://lh6.googleusercontent.com/-fPQ-TEfk9RE/AAAAAAAAAAI/AAAAAAAAAD4/W_oT9Nz5MpY/photo.jpg</item>
        <item>https://pbs.twimg.com/profile_images/431214974363385856/GAmxwTe-.png</item>
        <item>http://files.gamebanana.com/img/ico/sprays/515cc647f37a4.png</item>
    </array>
</resources>

I know this is a Frankenstein, I'd really appreciate some examples and suggestions. Thanks

Was it helpful?

Solution

The problem is on the:

new ScreenSlideActivity().new DownloadImagesTask()

As you can see you're creating a new ScreenSlideActivity and the AsyncTask belongs to this new one, instead of the current one being executed, which has inflated the layout and where the 'findById' works. Because you're using the AsyncTask created on the instance of the new instance, the code inside the AsyncTask.onPostExecute() will fail badly:

  ImageView mChart = (ImageView) findViewById(R.id.imageView1);

Why? because the findViewById() can't be executed because you're created the Activity instance by yourself, not managed by Android..so it's lost.

So instead of using this approach...try to delegate the onItemClick execution to a method inside the current running Activity instance..like this:

   listview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            String selectedPonyURL=listurl.get(position);
            ((ScreenSlideActivity)getActivity()).handleOnItemClick(selectedPonyURL);
        }

    });

and inside you will put the handling of starting the AsyncTask within the same context...like this you won't be creating a new ScreenSlideActivity object, you will be reusing the existing one...in ScreenSlideActivity:

...
     public void handleOnItemClick(String selectedPonyURL) {
        new DownloadImagesTask().execute(selectedPonyURL);
     }
 ...

Note: NEVER instantiate an Activity, its creation is managed by Android, if you do that, it will be just like a plain Java object, but problematic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top