انجمن سایت کلیدستان


رتبه موضوع:
  • 0 رای - 0 میانگین
  • 1
  • 2
  • 3
  • 4
  • 5
نوشتن کدها در یک کلاس، برای عدم تکرار کدنویسی (در برنامه نویسی اندروید)

نوشتن کدها در یک کلاس، برای عدم تکرار کدنویسی (در برنامه نویسی اندروید)

#1
درود
من یه اکتیویتی Main‌دارم که روش 20 تا imageview هست که باید با کلیک روی هرکدوم یه فایل mp3 دانلود شه.من میتونم برای یکیشون کد دانلود بنویسم اما برای نوشتن 20 تا کد تکراری زیاد میشه.میخوام از کلاس استفاده کنم ولی نمیدونم چطور.
با کلیک روی ایمیج ویو این خط اجرا میشه :

کد پی‌اچ‌پی:
new DownloadFileFromURL().execute(MY_URL); 

وبعد کدهای زیر که مربوط به دانلود فایل هست اجرا میشه و بدون مشکل کار میکنه :

کد پی‌اچ‌پی:
/**
     * Showing Dialog
     * */
    
protected Dialog onCreateDialog(int id) {
        switch (
id) {
        case 
progress_bar_type:
            
pDialog = new ProgressDialog(this);
            
pDialog.setMessage("Downloading file. Please wait...");
            
pDialog.setIndeterminate(false);
            
pDialog.setMax(100);
            
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            
pDialog.setCancelable(true);
            
pDialog.show();
            return 
pDialog;
        default:
            return 
null;
        }
    }
    
    public 
void downloadStreams() {
        try {
            
URL url = new URL(MY_URL);
            
HttpURLConnection c = (HttpURLConnectionurl.openConnection();
            
c.setRequestMethod("GET");
            
c.setDoOutput(true);
            
c.connect();

            
String PATH Environment.getExternalStorageDirectory()
                    .
getAbsolutePath() + "/Zanboor_Kochooloo_Va_Kerm.mp3";;
            
Log.v("log_tag""PATH: " PATH);
            
File file = new File(PATH);
            if (!
file.exists()) {
                
file.mkdirs();
            }
            
File outputFile = new File(file"/Zanboor_Kochooloo_Va_Kerm.mp3");
            
FileOutputStream fos = new FileOutputStream(outputFile);

            
InputStream is c.getInputStream();

            
byte[] buffer = new byte[1024];
            
int len1 0;
            while ((
len1 is.read(buffer)) != -1) {
                
fos.write(buffer0len1);
            }
            
fos.close();
            
is.close();
        } catch (
IOException e) {
            
Log.e("log_tag""Error: " e);
        }
        
Log.v("log_tag""Check: ");
    }
    
    class 
DownloadFileFromURL extends AsyncTask<StringStringString> {

        
/**
         * Before starting background thread Show Progress Bar Dialog
         * */
        
@Override
        
protected void onPreExecute() {
            
super.onPreExecute();
            
showDialog(progress_bar_type);
        }

        protected 
String doInBackground(String... f_url) {
            
int count;
            try {
                
URL url = new URL(f_url[0]);
                
URLConnection conection url.openConnection();
                
conection.connect();
                
// getting file length
                
int lenghtOfFile conection.getContentLength();

                
// input stream to read file - with 8k buffer
                
InputStream input = new BufferedInputStream(url.openStream(),
                        
8192);

                
// Output stream to write file
                
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory()+ "/Zanboor_Kochooloo_Va_Kerm.mp3");

                
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(data0count);
                }

                
// flushing output
                
output.flush();

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

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

            return 
null;
        }
        
        
/**
         * Updating progress bar
         * */
        
protected void onProgressUpdate(String... progress) {
            
// setting progress percentage
            
pDialog.setProgress(Integer.parseInt(progress[0]));
        }
        
        
        
/**
         * After completing background task Dismiss the progress dialog
         * **/
        
@Override
        
protected void onPostExecute(String file_url) {
            
// dismiss the dialog after the file was downloaded
            
dismissDialog(progress_bar_type);

            
// Displaying downloaded image into image view
            // Reading image path from sdcard
            
String imagePath Environment.getExternalStorageDirectory()
                    .
toString() + "/Zanboor_Kochooloo_Va_Kerm.mp3";
            
// setting downloaded into image view
            // my_image.setImageDrawable(Drawable.createFromPath(imagePath));
            //message.setText("File downloaded and saved to directory==>"+imagePath);
        
}

    } 

حالا مشکل من اینه که چطور باید این کدهای مربوط به دانلود رو در یک کلاس جدید تعریف کنم و چطور تو Main فراخوانیشون کنم؟سپاسگزار میشم راهنماییم کنید
پاسخ

نوشتن کدها در یک کلاس، برای عدم تکرار کدنویسی (در برنامه نویسی اندروید)

#2
سلام.
دسته بندی زیر را ببینید :

http://www.kelidestan.com/keys/categorie...ategory=30

اگر کدها به Context مربوط به Activity احتیاج داشتند، باید Context را به ورودی کلاس (Class) بدهید (برخی برنامه نویسان متوجه نمی شوند که چرا یک کد در Activity به درستی کار می کند، اما در کلاس، یا پیام خطا می دهد و یا اجرا نمی شود، دلیل این موارد، معمولا این است که کدها به Context آن Activity احتیاج دارند).


 
bookbook 
لطفا برای درج کد، از دکمه مخصوص درج کد در ادیتور انجمن استفاده کنید.
در مورد برنامه نویسی، مدیران تنها راهنمایی می کنند و نوشتن برنامه نهایی، به عهده کاربران می باشد (اینجا محلی برای یادگیری است، نه سفارش کدنویسی).
کاربران باید ابتدا خود به خطایابی برنامه بپردازند، نه اینکه به محض دیدن خطا، کدها را در انجمن، copy و paste کرده و از مدیران انتظار بررسی داشته باشند.
پاسخ
 سپاس شده توسط شماره مجازی امارات ، تلگرام ضد فیلتر 2023


پرش به انجمن:


کاربران در حال بازدید این موضوع: 1 مهمان