custom arrayadapter get data from asynctask

旧时模样 提交于 2020-01-05 09:30:16

问题


i trying to connect with themoviedb.orgbut there's some issues

MainActivityFragment.java

public class MainActivityFragment extends Fragment {

public Item[] dataAdapter ;


public MainActivityFragment() {
    this.updateData();
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Add this line in order for this fragment to handle menu events.
    setHasOptionsMenu(true);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_fragment, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.refresh_settings) {
        startActivity(new Intent(getActivity(),SettingsActivity.class));
        return true;
    }

    return super.onOptionsItemSelected(item);
}

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




    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

    CustomArrayAdapter adapter =new CustomArrayAdapter(this.getActivity() , R.layout.item , dataAdapter);
    // Get a reference to the ListView, and attach this adapter to it.
    GridView gridView = (GridView) rootView.findViewById(R.id.main_grid_view);
    gridView.setAdapter(adapter);


    return rootView;
}


private void updateData() {
    GetData DataTask = new GetData();

    DataTask.execute();
}

@Override
public void onStart() {
    super.onStart();
    this.updateData();
}



public class GetData extends AsyncTask<Void, Void, Item[]> {

    private final String LOG_TAG = GetData.class.getSimpleName();


    private Item[] getDataFromJson(String forecastJsonStr)
            throws JSONException{

        // These are the names of the JSON objects that need to be extracted.
        final String RESULTS = "results";
        final String IMG_PATH = "poster_path";
        final String TITLE = "title";

        JSONObject dataJson = new JSONObject(forecastJsonStr);
        JSONArray dataArray = dataJson.getJSONArray(RESULTS);

        int numofresults = dataArray.length();

        Item[] resultStrs = new Item[0];

        for(int i = 0; i < numofresults; i++) {
            // For now, using the format "Day, description, hi/low"
            String img_path;

            String title;


            JSONObject movieData = dataArray.getJSONObject(i);

            img_path = movieData.getString(IMG_PATH);
            img_path ="http://image.tmdb.org/t/p/w185"+img_path;
            title = movieData.getString(TITLE);
            Item element = new Item(img_path,title);

            resultStrs[i] = element;
        }
        return resultStrs;

    }

    @Override
    protected Item[] doInBackground(Void... strings) {




        // These two need to be declared outside the try/catch
        // so that they can be closed in the finally block.
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        // Will contain the raw JSON response as a string.
        String dataJsonStr = null;
        String parm = getString(R.string.pref_sort_most);
        String api_key = "API KEY";


        try {


            final String BASE_URL =
                    "http://api.themoviedb.org/3/discover/movie?";
            final String QUERY_PARAM = "sort_by";
            final String APPID_PARAM = "api_key";

            Uri builtUri = Uri.parse(BASE_URL).buildUpon()
                    .appendQueryParameter(QUERY_PARAM, parm)
                    .appendQueryParameter(APPID_PARAM, api_key)
                    .build();

            URL url = new URL(builtUri.toString());

            // Create the request to themoviedb.org, and open the connection
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            // Read the input stream into a String
            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                // Nothing to do.
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                // But it does make debugging a *lot* easier if you print out the completed
                // buffer for debugging.
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                // Stream was empty.  No point in parsing.
                return null;
            }
            dataJsonStr = buffer.toString();
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error ", e);

            return null;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e(LOG_TAG, "Error closing stream", e);
                }
            }
        }

        try {
            return getDataFromJson(dataJsonStr);
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
            e.printStackTrace();
        }
        return null;
    }

    @Override
     protected void onPostExecute(Item[] result) {
        if (result != null) {
            dataAdapter = result;
        }
            // New data is back from the server.  Hooray!
    }


}
}

CustomArrayAdapter.java

public class CustomArrayAdapter extends ArrayAdapter<Item> {

Context context;
int resource;
Item objects[] = null;

public CustomArrayAdapter(Context context, int resource, Item[] objects) {
    super(context, resource, objects);
    this.resource = resource;
    this.context = context;
    this.objects = objects;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    View row = convertView;
    DataHolder holder = null;

    if(row == null)
    {
        row = LayoutInflater.from(getContext()).inflate(
                R.layout.item, parent, false);

        holder = new DataHolder();
        holder.imgIcon = (ImageView)row.findViewById(R.id.image_main_item);
        holder.txtTitle = (TextView)row.findViewById(R.id.title_movie);

        row.setTag(holder);
    }else
    {
        holder = (DataHolder)row.getTag();
    }

    Item item = objects[position];
    holder.txtTitle.setText(item.title);
    Picasso.with(context).load(item.icon).into(holder.imgIcon);


    return row;
}




static class DataHolder
{
    ImageView imgIcon;
    TextView txtTitle;
}
}

Item.java

public class Item {
public String icon;
public String title;
public Item(){
    super();
}

public Item(String icon, String title) {
    super();
    this.icon = icon;
    this.title = title;
}
}

and here my Logcat

12-23 15:06:40.832 1644-1644/com.example.mohamed.movieapp E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.example.mohamed.movieapp, PID: 1644 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mohamed.movieapp/com.example.mohamed.movieapp.MainActivity}: android.view.InflateException: Binary XML file line #1: Error inflating class fragment at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) at android.app.ActivityThread.access$800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) Caused by: android.view.InflateException: Binary XML file line #1: Error inflating class fragment at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763) at android.view.LayoutInflater.inflate(LayoutInflater.java:482) at android.view.LayoutInflater.inflate(LayoutInflater.java:414) at android.view.LayoutInflater.inflate(LayoutInflater.java:365) at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256) at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109) at com.example.mohamed.movieapp.MainActivity.onCreate(MainActivity.java:19) at android.app.Activity.performCreate(Activity.java:5990) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)             at android.app.ActivityThread.access$800(ActivityThread.java:151)             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)             at android.os.Handler.dispatchMessage(Handler.java:102)             at android.os.Looper.loop(Looper.java:135)             at android.app.ActivityThread.main(ActivityThread.java:5254)             at java.lang.reflect.Method.invoke(Native Method)             at java.lang.reflect.Method.invoke(Method.java:372)             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) Caused by: java.lang.NullPointerException: storage == null at java.util.Arrays$ArrayList.(Arrays.java:38) at java.util.Arrays.asList(Arrays.java:155) at android.widget.ArrayAdapter.(ArrayAdapter.java:128) at com.example.mohamed.movieapp.CustomArrayAdapter.(CustomArrayAdapter.java:25) at com.example.mohamed.movieapp.MainActivityFragment.onCreateView(MainActivityFragment.java:78) at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1036) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1226) at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1328) at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2284) at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:111) at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:314) at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31) at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)             at android.view.LayoutInflater.inflate(LayoutInflater.java:482)             at android.view.LayoutInflater.inflate(LayoutInflater.java:414)             at android.view.LayoutInflater.inflate(LayoutInflater.java:365)             at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)             at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)             at com.example.mohamed.movieapp.MainActivity.onCreate(MainActivity.java:19)             at android.app.Activity.performCreate(Activity.java:5990)             at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)             at android.app.ActivityThread.access$800(ActivityThread.java:151)             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)             at android.os.Handler.dispatchMessage(Handler.java:102)             at android.os.Looper.loop(Looper.java:135)             at android.app.ActivityThread.main(ActivityThread.java:5254)             at java.lang.reflect.Method.invoke(Native Method)             at java.lang.reflect.Method.invoke(Method.java:372)             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

thnks for advice and interaction


回答1:


So during onCreateView which gets called early in life cylce, you are trying to create array adapter out of empty uninitialized array. Please move setAdapter call to your post execute.

Note: any particular reason to update data in constructor? You are anyway calling it onStart.



来源:https://stackoverflow.com/questions/34443009/custom-arrayadapter-get-data-from-asynctask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!