-2

这是我的代码。

public class Starter_info extends Activity implements OnClickListener, OnRatingBarChangeListener 
{
    private GestureDetector gestureDetector;
    String img_url, img_id, img_rat, img_name;
    ImageView iv;
    ImageView ib_dow, ib_wal;
    ImageView btn_rate;
    ProgressBar pb;
    Dialog dialog;
    int downloadedSize = 0;
    int totalSize = 0;
    TextView cur_val;

    /* Rating Bar Dialog */
    Dialog rankDialog;
    RatingBar ratingBar,pre_rating;
    float cus_rating;

    ProgressDialog progDailog;

    // JSON Node names
    private static final String TAG_CONTACTS = "Demo";
    private static final String TAG_ID = "id";
    private static final String TAG_TITLE = "title";
    private static final String TAG_RATING = "Rating";
    private static final String TAG_CATEGORY = "Category";
    private static final String TAG_IMAGE = "Images";
    private static final String TAG_DOWNLOAD =  "Downloads";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.starter_info);

        Log.v("starter Info Heap","Max Mem in MB:"+(Runtime.getRuntime().maxMemory()/1024/1024));
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        gestureDetector = new GestureDetector(new SwipeGestureDetector());

        ImageView rankBtn = (ImageView) findViewById(R.id.btn_starter_info_rate);
        rankBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                rankDialog = new Dialog(Starter_info.this,
                        R.style.FullHeightDialog);
                rankDialog.setContentView(R.layout.rating_bar);
                rankDialog.setCancelable(true);
                ratingBar = (RatingBar) rankDialog
                        .findViewById(R.id.dialog_ratingbar);
                float userRankValue = 0;
                // ratingBar.setRating(userRankValue);
                ratingBar
                        .setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
                            @Override
                            public void onRatingChanged(RatingBar ratingBar,
                                    float rating, boolean fromUser) {
                                // TODO Auto-generated method stub
                                cus_rating = rating;
                            }
                        });

                Button updateButton = (Button) rankDialog
                        .findViewById(R.id.rank_dialog_button);
                updateButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(Starter_info.this,
                                "Rating is" + cus_rating, Toast.LENGTH_LONG)
                                .show();

                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost(
                                "http://vaibhavtech.com/work/android/rating.php");

                        try {
                            // Add your data
                            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                                    1);
                            nameValuePairs.add(new BasicNameValuePair("id",
                                    img_id));
                            nameValuePairs.add(new BasicNameValuePair("rating",
                                    "" + cus_rating));
                            httppost.setEntity(new UrlEncodedFormEntity(
                                    nameValuePairs));

                            // Execute HTTP Post Request

                            ResponseHandler<String> responseHandler = new BasicResponseHandler();
                            String response = httpclient.execute(httppost,
                                    responseHandler);

                            // This is the response from a php application
                            String reverseString = response;
                            Log.i("response", reverseString);

                        } catch (ClientProtocolException e) {
                            Log.i("CPE response ", e.toString());
                            // TODO Auto-generated catch block
                        } catch (IOException e) {
                            Log.i("IOException response ", e.toString());
                            // TODO Auto-generated catch block
                        }

                        rankDialog.dismiss();
                    }
                });
                // now that the dialog is set up, it's time to show it
                rankDialog.show();
            }
        });

        img_url = MyFragment.img_url;
        img_id = MyFragment.img_id;
        img_rat = MyFragment.img_rating;
        img_name = MyFragment.img_name;
        ib_dow = (ImageView) findViewById(R.id.ib_starter_info_down);
        ib_wal = (ImageView) findViewById(R.id.ib_starter_info_Wall);
        ib_dow.setOnClickListener(this);
        ib_wal.setOnClickListener(this);
        pre_rating=(RatingBar) findViewById(R.id.rb_starter_info_pre_rating);
        pre_rating.setRating(Float.parseFloat(img_rat));

        iv = (ImageView) findViewById(R.id.iv_starter_info);


      //        Log.i("image id", img_id);
    //      Log.i("image name", img_name);
       //       Log.i("image url", img_url);
         //     Log.i("image rat", img_rat);
        int loader = R.drawable.load;
        ImageLoader imgLoader = new ImageLoader(getApplicationContext());
        imgLoader.DisplayImage(img_url, loader, iv);
    }
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        switch(item.getItemId())
        {
        case android.R.id.home:
            onBackPressed();
            return true;
            case R.id.home:
                Intent intent = new Intent(this, Category.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        switch (v.getId()) {
        case R.id.ib_starter_info_down:

            showProgress(img_url);

            new Thread(new Runnable() {
                public void run() {
                    downloadFile();
                }
            }).start();

            break;
        case R.id.ib_starter_info_Wall:

            showProgress(img_url);

            new Thread(new Runnable() {
                public void run() {
                    downloadFile_Wall();
                    WallpaperManager myWallpaperManager = WallpaperManager
                            .getInstance(getApplicationContext());
                    Bitmap o = BitmapFactory.decodeFile("/sdcard/." + img_name);
                    try {
                        myWallpaperManager.setBitmap(o);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }).start();
            break;
        case R.id.btn_starter_info_rate:

            break;
        }
    }

    @Override
    public void onRatingChanged(RatingBar ratingBar, float rating,
            boolean fromUser) {
        // TODO Auto-generated method stub

        Toast.makeText(this, "Ypur Rating is" + rating, Toast.LENGTH_LONG)
                .show();
    }

    void downloadFile() {

        try {
            URL url = new URL(img_url);
            HttpURLConnection urlConnection = (HttpURLConnection) url
                    .openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            // connect
            urlConnection.connect();

            // set the path where we want to save the file
            File SDCardRoot = Environment.getExternalStorageDirectory();
            // create a new file, to save the downloaded file
            File file = new File(SDCardRoot, img_name);

            FileOutputStream fileOutput = new FileOutputStream(file);

            // Stream used for reading the data from the internet
            InputStream inputStream = urlConnection.getInputStream();

            // this is the total size of the file which we are downloading
            totalSize = urlConnection.getContentLength();

            runOnUiThread(new Runnable() {
                public void run() {
                    pb.setMax(totalSize);
                }
            });

            // create a buffer...
            byte[] buffer = new byte[1024];
            int bufferLength = 0;

            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fileOutput.write(buffer, 0, bufferLength);
                downloadedSize += bufferLength;
                // update the progressbar //
                runOnUiThread(new Runnable() {
                    public void run() {
                        pb.setProgress(downloadedSize);
                        float per = ((float) downloadedSize / totalSize) * 100;
                        cur_val.setText("Downloaded " + downloadedSize
                                + "KB / " + totalSize + "KB (" + (int) per
                                + "%)");
                    }
                });
            }
            // close the output stream when complete //
            fileOutput.close();
            runOnUiThread(new Runnable() {
                public void run() {
                    // pb.dismiss(); // if you want close it..
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost(
                            "http://vaibhavtech.com/work/android/downloads.php");

                    try {
                        // Add your data
                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                                1);
                        nameValuePairs
                                .add(new BasicNameValuePair("id", img_id));

                        httppost.setEntity(new UrlEncodedFormEntity(
                                nameValuePairs));

                        // Execute HTTP Post Request

                        ResponseHandler<String> responseHandler = new BasicResponseHandler();
                        String response = httpclient.execute(httppost,
                                responseHandler);

                        // This is the response from a php application
                        String reverseString = response;
                        Log.i("response", reverseString);

                    } catch (ClientProtocolException e) {
                        Log.i("CPE response ", e.toString());
                        // TODO Auto-generated catch block
                    } catch (IOException e) {
                        Log.i("IOException response ", e.toString());
                        // TODO Auto-generated catch block
                    }
                    dialog.dismiss();
                    Toast.makeText(Starter_info.this, "SuccessFully Download..",
                            Toast.LENGTH_LONG).show();
                }
            });

        } catch (final MalformedURLException e) {
            showError("Error : MalformedURLException " + e);
            e.printStackTrace();
        } catch (final IOException e) {
            showError("Error : IOException " + e);
            e.printStackTrace();
        } catch (final Exception e) {
            showError("Error : Please check your internet connection " + e);
        }
    }

    // For WallPaper Set Click Here.............
    void downloadFile_Wall() {
        try {
            URL url = new URL(img_url);
            HttpURLConnection urlConnection = (HttpURLConnection) url
                    .openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            // connect
            urlConnection.connect();
            // set the path where we want to save the file
            File SDCardRoot = Environment.getExternalStorageDirectory();
            // create a new file, to save the downloaded file
            File file = new File(SDCardRoot, "." + img_name);
            FileOutputStream fileOutput = new FileOutputStream(file);
            // Stream used for reading the data from the internet
            InputStream inputStream = urlConnection.getInputStream();
            // this is the total size of the file which we are downloading
            totalSize = urlConnection.getContentLength();

            runOnUiThread(new Runnable() {
                public void run() {
                    pb.setMax(totalSize);
                }
            });
            // create a buffer...
            byte[] buffer = new byte[1024];
            int bufferLength = 0;
            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fileOutput.write(buffer, 0, bufferLength);
                downloadedSize += bufferLength;
                // update the progressbar //
                runOnUiThread(new Runnable() {
                    public void run() {
                        pb.setProgress(downloadedSize);
                        float per = ((float) downloadedSize / totalSize) * 100;
                        cur_val.setText("Please Wait...");
                    }
                });
            }
            // close the output stream when complete //
            fileOutput.close();
            runOnUiThread(new Runnable() {
                public void run() {
                    // pb.dismiss(); // if you want close it..
                    Toast.makeText(Starter_info.this, "Changes Apply SuccessFully..",
                            Toast.LENGTH_LONG).show();
                    dialog.dismiss();
                    // startActivity(new
                    // Intent(Starter_info.this,CropImage.class));
                }
            });

        } catch (final MalformedURLException e) {
            showError("Error : MalformedURLException " + e);
            e.printStackTrace();
        } catch (final IOException e) {
            showError("Error : IOException " + e);
            e.printStackTrace();
        } catch (final Exception e) {
            showError("Error : Please check your internet connection " + e);
        }
    }

    void showError(final String err) {
        runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(Starter_info.this, err, Toast.LENGTH_LONG)
                        .show();
            }
        });
    }

    void showProgress(String file_path) {
        dialog = new Dialog(Starter_info.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.myprogressdialog);
        dialog.setTitle("Download Progress");

        TextView text = (TextView) dialog.findViewById(R.id.tv1);
        text.setText("Downloading file from ... " + file_path);
        cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
        cur_val.setText("Starting download...");
        //dialog.show();

        pb = (ProgressBar) dialog.findViewById(R.id.progress_bar);
        pb.setProgress(0);
        pb.setProgressDrawable(getResources().getDrawable(
                R.drawable.green_progress));

        Toast.makeText(getApplicationContext(), "Please Wait..Process Run In BackGround", Toast.LENGTH_LONG).show();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (gestureDetector.onTouchEvent(event)) {
            return true;
        }
        return super.onTouchEvent(event);
    }

    private void onLeftSwipe() {
      //        // Do something
           //       MyFragment.img_url = "http://vaibhavtech.com/work/wallpaper/upload/Picture-6.jpg";
         //     MyFragment.img_id = "75";
        //      MyFragment.img_rating = "4";
        //      MyFragment.img_name = "Picture-6.jpg";
           //       Log.i("Swipe", "Left Swipe");
    Toast.makeText(Starter_info.this, "Left Swipe", Toast.LENGTH_LONG).show();
      //        startActivity(new Intent(Starter_info.this, Starter_info.class));
        JSONArray contacts = null;

        Swipe_parser jParser = new Swipe_parser();

        // getting JSON string from URL
        String url="http://vaibhavtech.com/work/android/wallpaper_data.php?next="+img_id;
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of Contacts
            contacts = json.getJSONArray(TAG_CONTACTS);

            // looping through All Contacts
            for(int i = 0; i < contacts.length(); i++){
                JSONObject c = contacts.getJSONObject(i);

                // Storing each json item in variable
                String id = c.getString(TAG_ID);
                String title = c.getString(TAG_TITLE);
                String rating = c.getString(TAG_RATING);
                String image = c.getString(TAG_IMAGE);
                String category = c.getString(TAG_CATEGORY);
                String download=c.getString(TAG_DOWNLOAD);
                Log.i("id", id);
                Log.i("titleq", title);
                Log.i("rating", rating);
                Log.i("image",image);
                Log.i("catet", category);
                Log.i("download", download);


                   MyFragment.img_url="http://vaibhavtech.com/work/android/admin/upload/"+image;
                 MyFragment.img_id=id;
                 MyFragment.img_rating=rating;
                 MyFragment.img_name=image;
            }
            startActivity(new Intent(Starter_info.this,Starter_info.class));
            finish();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void onRightSwipe() {
        // Do something

        Log.i("Swipe", "Right Swipe");
        Toast.makeText(Starter_info.this, "Right Swipe", Toast.LENGTH_LONG)
                .show();
             JSONArray contacts = null;

        Swipe_parser jParser = new Swipe_parser();

        // getting JSON string from URL
        String url="http://vaibhavtech.com/work/android/wallpaper_data.php?pre="+img_id;
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of Contacts
            contacts = json.getJSONArray(TAG_CONTACTS);

            // looping through All Contacts
            for(int i = 0; i < contacts.length(); i++){
                JSONObject c = contacts.getJSONObject(i);

                // Storing each json item in variable
                String id = c.getString(TAG_ID);
                String title = c.getString(TAG_TITLE);
                String rating = c.getString(TAG_RATING);
                String image = c.getString(TAG_IMAGE);
                String category = c.getString(TAG_CATEGORY);
                String download=c.getString(TAG_DOWNLOAD);
                Log.i("id", id);
                Log.i("titleq", title);
                Log.i("rating", rating);
                Log.i("image",image);
                Log.i("catet", category);
                Log.i("download", download);


                 MyFragment.img_url="http://vaibhavtech.com/work/android/admin/upload/"+image;
                 MyFragment.img_id=id;
                 MyFragment.img_rating=rating;
                 MyFragment.img_name=image;
            }
            startActivity(new Intent(Starter_info.this,Starter_info.class));
            finish();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // Private class for gestures
    private class SwipeGestureDetector extends SimpleOnGestureListener {
        // Swipe properties, you can change it to make the swipe
        // longer or shorter and speed
        private static final int SWIPE_MIN_DISTANCE = 120;
        private static final int SWIPE_MAX_OFF_PATH = 200;
        private static final int SWIPE_THRESHOLD_VELOCITY = 200;

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                float velocityY) {
            try {
                float diffAbs = Math.abs(e1.getY() - e2.getY());
                float diff = e1.getX() - e2.getX();

                if (diffAbs > SWIPE_MAX_OFF_PATH)
                    return false;
                // Left swipe
                if (diff > SWIPE_MIN_DISTANCE
                        && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    Starter_info.this.onLeftSwipe();

                    // Right swipe
                } else if (-diff > SWIPE_MIN_DISTANCE
                        && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    Starter_info.this.onRightSwipe();
                }
            } catch (Exception e) {
                Log.e("YourActivity", "Error on gestures");
            }
            return false;
                }
          }
       }

这是我的日志:

11-11 04:54:58.057: V/starter Info Heap(3122): Max Mem in MB:32
11-11 04:54:58.077: D/AndroidRuntime(3122): Shutting down VM
     11-11 04:54:58.097: W/dalvikvm(3122): threadid=1: thread exiting with uncaught  exception (group=0x41465700)
  11-11 04:54:58.187: E/AndroidRuntime(3122): FATAL EXCEPTION: main
   11-11 04:54:58.187: E/AndroidRuntime(3122): java.lang.RuntimeException: Unable to start activity             ComponentInfo{com.example.target_wallpaper77/com.example.target_wallpaper77.Starter_info}: java.lang.NumberFormatException: Invalid float: "2:00 h"
    11-11 04:54:58.187: E/AndroidRuntime(3122):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
    11-11 04:54:58.187: E/AndroidRuntime(3122):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
        11-11 04:54:58.187: E/AndroidRuntime(3122):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
    11-11 04:54:58.187: E/AndroidRuntime(3122):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
   11-11 04:54:58.187: E/AndroidRuntime(3122):  at android.os.Handler.dispatchMessage(Handler.java:99)
   11-11 04:54:58.187: E/AndroidRuntime(3122):  at android.os.Looper.loop(Looper.java:137)
   11-11 04:54:58.187: E/AndroidRuntime(3122):  at android.app.ActivityThread.main(ActivityThread.java:5103)
  11-11 04:54:58.187: E/AndroidRuntime(3122):   at java.lang.reflect.Method.invokeNative(Native Method)
  11-11 04:54:58.187: E/AndroidRuntime(3122):   at java.lang.reflect.Method.invoke(Method.java:525)
 11-11 04:54:58.187: E/AndroidRuntime(3122):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
       11-11 04:54:58.187: E/AndroidRuntime(3122):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
   11-11 04:54:58.187: E/AndroidRuntime(3122):  at dalvik.system.NativeStart.main(Native Method)
  11-11 04:54:58.187: E/AndroidRuntime(3122): Caused by: java.lang.NumberFormatException: Invalid float: "2:00 h"
   11-11 04:54:58.187: E/AndroidRuntime(3122):  at  java.lang.StringToReal.invalidReal(StringToReal.java:63)
   11-11 04:54:58.187: E/AndroidRuntime(3122):  at java.lang.StringToReal.parseFloat(StringToReal.java:310)
11-11 04:54:58.187: E/AndroidRuntime(3122):     at  java.lang.Float.parseFloat(Float.java:300)
  11-11 04:54:58.187: E/AndroidRuntime(3122):   at com.example.target_wallpaper77.Starter_info.onCreate(Starter_info.java:198)
11-11 04:54:58.187: E/AndroidRuntime(3122):     at android.app.Activity.performCreate(Activity.java:5133)
  11-11 04:54:58.187: E/AndroidRuntime(3122):   at   android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
 11-11 04:54:58.187: E/AndroidRuntime(3122):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
  11-11 04:54:58.187: E/AndroidRuntime(3122):   ... 11 more
11-11 04:59:58.414: I/Process(3122): Sending signal. PID: 3122 SIG: 9
11-11 04:59:59.277: D/dalvikvm(3179): GC_FOR_ALLOC freed 72K, 7% free 2688K/2880K, paused 50ms, total 52ms
 11-11 04:59:59.287: I/dalvikvm-heap(3179): Grow heap (frag case) to 3.343MB for 635812-byte allocation
11-11 04:59:59.407: D/dalvikvm(3179): GC_FOR_ALLOC freed 2K, 6% free 3306K/3504K, paused  126ms, total 126ms
11-11 04:59:59.450: D/dalvikvm(3179): GC_FOR_ALLOC freed <1K, 6% free 3307K/3504K, paused 33ms, total 33ms
 11-11 04:59:59.467: I/dalvikvm-heap(3179): Grow heap (frag case) to 4.807MB for 1536016-byte allocation
 11-11 04:59:59.597: D/dalvikvm(3179): GC_FOR_ALLOC freed <1K, 5% free 4807K/5008K, paused 128ms, total 128ms
 11-11 04:59:59.867: D/dalvikvm(3179): GC_FOR_ALLOC freed 1K, 4% free 5412K/5616K, paused 27ms, total 27ms
 11-11 05:00:00.067: V/Category Heap(3179): Max Mem in MB:32
    11-11 05:00:00.267: D/gralloc_goldfish(3179): Emulator without GPU emulation detected.
4

1 回答 1

1

Float.parseFloat将无法解析,因为它不理解“2:00 h”,您将需要以某种方式解析 2.0f。parseFloat无法解析字符和符号。

于 2013-11-11T10:25:19.100 回答