为什么BitmapFactory.decodeStream(input)在我的代码中返回null而我的照片没有显示?

时间:2014-11-22 02:58:02

标签: android listview bitmap android-asynctask download

我想阅读一些图书的数据,并在列表视图中显示它们并使用位图显示图书的图片。我可以显示其他信息,但我无法显示图片,我无法找到原因,因为我做了所需的位图需求,因为我使用我的照片显示的AsyncTask方法! 而且很棒的是当我点击一个项目,下载布局正确地显示书的图片时,当我再次从第一个位置打开AllBooksActivity时,它正好显示图片!@ / p>

这是我的AllBooksActivity代码:

public class AllBooksActivity extends Activity {
        public ListItem adapter;
        public ListView allbooklist;

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

            new loadingbooks().execute();
        }

        private class loadingbooks extends AsyncTask<String, String, String> {


            private ProgressDialog pDialog;

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

                pDialog = new ProgressDialog(AllBooksActivity.this);
                pDialog.setMessage("کتابها در حال بارگذاری، لطفا منتظر بمانید...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(false);
                pDialog.show();
            }

            @Override
            protected String doInBackground(String... args) {

                String res = JSONCommands.readData(MainActivity.params);
                return res;
            }

            @Override
            protected void onPostExecute(String res) {
                if(res != null){
                    pDialog.dismiss();
                    AllBooksActivity.this.getActionBar().setTitle(MainActivity.how);

                    allbooklist = (ListView) findViewById(R.id.list_all);
                    allbooklist.setOnItemClickListener(new OnItemClickListener() {

                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            Intent in = new Intent(getApplicationContext(), DownloadActivity.class);

                            in.putExtra("MyClass", MainActivity.books_array.get(position)); 

                            startActivity(in);
                        }

                    });
                    adapter = new ListItem(AllBooksActivity.this,  MainActivity.books_array);
                    allbooklist.setAdapter(adapter);
                    }
                    else {
                        pDialog.dismiss();
                        AlertDialog.Builder builder = new AlertDialog.Builder(AllBooksActivity.this)
                                .setTitle("خطا در برقراری ارتباط با سرور")
                                .setMessage("نمایش کتاب ناموفق :( اتصالات را بررسی کنید.");
                        builder.create().show();
                    }
           }
        }

这是我的列表适配器代码:

public class ListItem extends BaseAdapter {

    private int count;
    private Context context;
    private ArrayList<ShowBook> bookArray;

    public ListItem(Context context,  ArrayList<ShowBook> bookArray) {
        this.count = bookArray.size();
        this.context = context;
        this.bookArray = bookArray;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return count;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        View row = inflater.inflate(R.layout.list_item, parent, false);
        TextView namketabltxt, nevisandeltxt, mozooltxt, qeymatltxt;
        ImageView tasvirlimg;

        namketabltxt = (TextView) row.findViewById(R.id.ltxt_namketab);
        nevisandeltxt = (TextView) row.findViewById(R.id.ltxt_nevisande);
        mozooltxt = (TextView) row.findViewById(R.id.ltxt_mozoo);
        qeymatltxt = (TextView) row.findViewById(R.id.ltxt_qeymat);
        tasvirlimg = (ImageView)row.findViewById(R.id.limg_tasvir);

        namketabltxt.setText(MainActivity.books_array.get(position).namketab);
        nevisandeltxt.setText(MainActivity.books_array.get(position).nevisande);
        mozooltxt.setText(MainActivity.books_array.get(position).mozoo);
        qeymatltxt.setText(MainActivity.books_array.get(position).qeymat);
        JSONCommands.getpic(MainActivity.books_array.get(position).tasvir, tasvirlimg);

        return row;
    }

}

这是我的DownloadActivity代码:

@SuppressLint("ShowToast") public class DownloadActivity extends Activity {

    TextView namketabdtxt, nevisandedtxt, mozoodtxt, qeymatdtxt, uplodkonandedtxt;
    ImageView tasvirdimg;
    Button dlbtn;
    RatingBar rb;

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

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy); 

    namketabdtxt = (TextView) findViewById(R.id.dtxt_namketab);
    nevisandedtxt = (TextView) findViewById(R.id.dtxt_nevisande);
    mozoodtxt = (TextView) findViewById(R.id.dtxt_mozoo);
    uplodkonandedtxt = (TextView) findViewById(R.id.dtxt_uplodkonande);
    qeymatdtxt = (TextView) findViewById(R.id.dtxt_qeymat);
    tasvirdimg = (ImageView) findViewById(R.id.dimg_tasvir);
    dlbtn = (Button)findViewById(R.id.btn_dl);
    rb = (RatingBar) findViewById(R.id.ratingBar1);

    final ShowBook book = (ShowBook) getIntent().getSerializableExtra("MyClass");

    this.getActionBar().setTitle(book.namketab);

    namketabdtxt.setText(book.namketab);
    nevisandedtxt.setText(book.nevisande);
    mozoodtxt.setText(book.mozoo);
    uplodkonandedtxt.setText(book.uplodkonande);
    qeymatdtxt.setText(book.qeymat);
    JSONCommands.getpic(book.tasvir, tasvirdimg);

    dlbtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            DownloadFileFromURL downloader = new DownloadFileFromURL();
            //downloader.setDownloadedFileName()
            String name = book.fileketab.substring(book.fileketab.lastIndexOf("/") + 1); 
            downloader.setDownloadedFileName(name);
            downloader.execute(JSONCommands.firstURL + book.fileketab);
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.download, menu);
    return true;
}


private class DownloadFileFromURL extends AsyncTask<String, String, String> {
    private String downloadedfileName;

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub

            Toast.makeText(getApplicationContext(), "بارگذاری کتاب باموفقیت انجام شد", Toast.LENGTH_LONG).show();
            Toast.makeText(getApplicationContext(), "برای دیدن آن به کتاب‌خانه مراجعه نمایید", Toast.LENGTH_LONG).show();
    }
    public void setDownloadedFileName(String downloadedfileName){
        this.downloadedfileName = downloadedfileName;
    }

    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... surl) {

        int count;
        try {
            URL url = new URL(surl[0]);
            URLConnection conection = url.openConnection();
            conection.connect();

            // this will be useful so that you can show a typical 0-100%
            // progress bar
            int lenghtOfFile = conection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream(),
                    8192);

            // Output stream
            //OutputStream output = new FileOutputStream(Environment
            //        .getExternalStorageDirectory().toString()
            //        + "/data/" + downloadedfileName);
            OutputStream output = new FileOutputStream(getFilesDir()+File.separator +downloadedfileName);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
                // publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return null;
    }

}

/**
 * After completing background task called
 * **/

}

这是我使用Bitmap的getpic代码(这个函数在我的JSONCommands类中,这就是为什么我把它们称为&#34; JSONCommands.getpic&#34;):

public static void getpic(String str, ImageView tasvir){
        Bitmap bitmap; 
        if(str != null){
            bitmap = getBitmapFromURL(firstURL+ str);
            if(bitmap!=null){
            tasvir.setImageBitmap(bitmap); 
            }
            else{
                tasvir.setImageResource(R.drawable.p3_books);
            }
        }
        else{ 
            tasvir.setImageResource(R.drawable.p3_books);
            }
    }

    public static Bitmap getBitmapFromURL(String src) {
        try {
            URL url = new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            connection.disconnect();
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

我无法找到解决方案而且它让我发疯了:)请帮忙,坦克你。

0 个答案:

没有答案