簡體   English   中英

Android:adapter.notifydatasetchanged()

[英]Android: adapter.notifydatasetchanged()

我想創建一個動態GridView,當我點擊我的選項meny時,我刷新我的asyncTask,然后我從postExecute得到所有結果,並通知我的適配器刷新! 但我不工作請幫助我!

GridView grid;
ImageAdapter adapter;

ArrayList<String> arrayThumbs = new ArrayList<String>();
ArrayList<String> arrayBig_image = new ArrayList<String>();
ArrayList<String> arrayAuthor = new ArrayList<String>();
ArrayList<String> arrayDescription = new ArrayList<String>();
ArrayList<String> arrayDate = new ArrayList<String>();

String[] arraymThumbs;
String[] arrayBimages;
String[] arrayauthor;
String[] arraydescription;
String[] arraydate;

final static String TAG_ITEM = "img_list";
final static String TAG_THUMBNAILS = "thumbnail";
final static String TAG_BIG_IMAGE = "big_image";
final static String TAG_AUTHOR = "author";
final static String TAG_DESCRIPTION = "description";
final static String TAG_DATE = "event_date";

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

        backTask();


        grid = (GridView) findViewById(R.id.grid);
        grid.setAdapter(adapter);
        grid.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterview, View view,  int position, long id) {
                Intent intent = new Intent(MainActivity.this, ImageGallery.class);
                intent.putExtra("position", position);
                intent.putExtra("big_images", arrayBimages);
                intent.putExtra("author", arrayauthor);
                intent.putExtra("description", arraydescription);
                intent.putExtra("date", arraydate);
                startActivity(intent);
            }
        }); 

}

public boolean onCreateOptionsMenu(Menu menu){
    getMenuInflater().inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);

}

public boolean onOptionsItemSelected(MenuItem item){        
    switch (item.getItemId()) {
    case R.id.refresh:
        backTask();
        break;
    }
    return super.onOptionsItemSelected(item);
}

public void backTask(){

    BackTask task = new BackTask();
    task.execute();



    try {
        JSONObject result = task.get();
        if(result != null){
        JSONArray jarray = result.getJSONArray(TAG_ITEM);
        for(int i = 0; i < jarray.length(); i++){
            JSONObject jrss = jarray.getJSONObject(i);
            arrayThumbs.add(jrss.getString(TAG_THUMBNAILS));
            arrayBig_image.add(jrss.getString(TAG_BIG_IMAGE));
            arrayAuthor.add(jrss.getString(TAG_AUTHOR));
            arrayDescription.add(jrss.getString(TAG_DESCRIPTION));
            arrayDate.add(jrss.getString(TAG_DATE));

            Log.d("LLLLLOOOOGGGG", jrss.getString("author")+"\n");
        }}
        else{
            AlertDialog.Builder alertNetworkError = new AlertDialog.Builder(this);
            alertNetworkError.setMessage("нет подключения к интернету");
            alertNetworkError.setNegativeButton("Выйти", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();                           
                }                       
            });
            alertNetworkError.create();
            alertNetworkError.show();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    arraymThumbs = new String[arrayThumbs.size()];
    arraymThumbs = arrayThumbs.toArray(arraymThumbs);

    arrayBimages = new String[arrayBig_image.size()];
    arrayBimages = arrayBig_image.toArray(arrayBimages);

    arrayauthor = new String[arrayAuthor.size()];
    arrayauthor = arrayAuthor.toArray(arrayauthor);

    arraydescription = new String[arrayDescription.size()];
    arraydescription = arrayDescription.toArray(arraydescription);

    arraydate = new String[arrayDate.size()];
    arraydate = arrayDate.toArray(arraydate);
    adapter = new ImageAdapter(MainActivity.this, arraymThumbs);
    adapter.notifyDataSetChanged();



}

我的圖像適配器在這里我從asyncTask得到所有結果並將拇指圖像打印到我的GridView

public class ImageAdapter extends BaseAdapter {

    public Context mContext;
    String[] mThumbs;
    public LayoutInflater inflater;
    public DisplayImageOptions options;
    public ImageLoader imageLoader;


    public ImageAdapter (Context c, String[] arrayhumbss){
        mContext = c;
        inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mThumbs = arrayhumbss;
        options  = new DisplayImageOptions.Builder()
                .showStubImage(R.drawable.ic_contact_picture_2)
                .showImageForEmptyUri(R.drawable.ic_launcher)
                .cacheInMemory()
                .cacheOnDisc()
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(c));
    }


    @Override
    public int getCount() {
        return mThumbs.length;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {     
        final ImageView imageView;
        if (convertView == null) {
            imageView = (ImageView) inflater.inflate(R.layout.grid_item, parent, false);
        } else {
            imageView = (ImageView) convertView;
        }

        imageLoader.displayImage(mThumbs[position], imageView, options);

        return imageView;
    }



}

這是我的BACKTASK

public class BackTask extends AsyncTask<String, Void, JSONObject>{  

@Override
protected JSONObject doInBackground(String... params) {
    InputStream ips = null; 
    JSONObject jsonObj = null;
    String json = "";       
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(new HttpPost("http://192.168.1.179/lenta/image.js"));                
        ips = response.getEntity().getContent();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader bufff = new BufferedReader(new InputStreamReader(ips, "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = bufff.readLine()) != null){
            sb.append(line + "\n");                 
        }
        ips.close();
        json = sb.toString();       
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        jsonObj = new JSONObject(json);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return jsonObj;     

    }

    @Override
    protected void onPostExecute(JSONObject result){
        super.onPostExecute(result);



        }

}

在這里我從url處理我的json,在MainActivity中我得到這個表單task.get()

在此行之后添加grid.setAdapter(adapter)

 adapter = new ImageAdapter(MainActivity.this, arraymThumbs);

希望這能解決你的問題。

編輯:PS似乎你需要閱讀一些東西,因為我認為你不完全了解適配器是什么以及如何使用它。

用這個 :

adapter = new ImageAdapter(YourActivity.this, arraymThumbs); 
myGridView.setAdapter(adapter);

希望這對你有所幫助。

謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM