ArrayLIst保持为空,不在android studio中添加jsoup解析元素

时间:2018-05-28 20:37:38

标签: java android parsing arraylist jsoup

我一直在努力解决这个问题。我有一个名为imgURLS的ArrayLIst,我想添加我使用jsoup从我的网站解析的网址。但imgURLS总是空的。我在eclipse上尝试了jsoup解析,但它确实有效。当我在create方法中添加字符串而不是在URLcollector(这是一个异步实现)中添加字符串时,arraylist工作。

我的代码假设首先从我的网站获取图片网址。然后把它们放在arrayLIst中。然后使用arrayList元素(链接)在imageView中看到。

现在除了将解析后的图像链接存储在arrayList中之外,其他所有工作都有效。我需要帮助才能做到这一点。我愿意使用另一个像arrayList这样的容器,如果这样可以让事情变得更容易。感谢

<%= form_tag( '/welcome/how_much', post: true, remote: true) do %>
 <span id="questions">
  <h5 class="label">Estimated new home cost?</h5>
   <%= text_field(:amount, {id: "house_amount", placeholder: "ex. 100,000"}, class: "form-control form-control-lg") %>
 </span>
 <span id="questions">
  <h5 class="label">Estimated payment for a new home?</h5>
   <%= text_field(:high_rent, {id: "high_rent", placeholder: "ex. 1,200"}, class: "form-control form-control-lg") %>
 </span>
 <span id="questions">
  <h5 class="label">Current Monthly Rent?</h5>
   <%= text_field(:current_rent, {id: "current_rent", placeholder: "ex. 800"}, class: "form-control form-control-lg") %>
 </span>
 <%= submit_tag("See how quickly you can buy a home", data: {'data-toggle' => "modal", 'data_target' => "#savings_modal"}, class: "btn btn-success btn-lg") %>

<!-- Modal for sign-up -->
<div class="modal" id="savings_modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <h3 class="modal-title" id="savingsModalTitle">You could be ready to buy in <%= @months_to_buy %> months</h3>
      <h5 class="modal-title">and have <%= @total_savings %>* to put towards a down payment & a drastically increased credit score using LikeHome</h5>
      <div class="modal-body">
        <h4>Sign-up Now to get started!</h4>
        <%= render '_tenant_signup_modal_form.html.erb' %>
      </div>
    </div>
  </div>
</div>

错误

public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
ImageView imageView;
int count = 0;
String websteURL = "https://wubewallpapers.wordpress.com/";
//String url1 = "https://wubewallpapers.files.wordpress.com/2018/03/landscape.jpg?w=134&h=201&zoom=2";
ArrayList<String> imgURLS = new ArrayList<>();
//ArrayList<String> imgURLS2 = new ArrayList<>();
//ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout. ,imgURLS );

Button setBKG;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageView = findViewById(R.id.imageView);
    setBKG = findViewById(R.id.setBKG);

    new URLcollector().execute(websteURL);
    loadImageFromUrl(imgURLS.get(count));


    imageView.setOnTouchListener(new OnSwipeTouchListener(MainActivity.this) {
        public void onSwipeRight() {
            Toast.makeText(MainActivity.this, "right : " + imgURLS.size(), Toast.LENGTH_SHORT).show();
            if (count == imgURLS.size() - 1) {
                count = 0;
            } else {
                count++;
            }
            loadImageFromUrl(imgURLS.get(count));
        }

        public void onSwipeLeft() {
            // Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
            if (count == 0) {
                count = imgURLS.size() - 1;
            } else {
                count -= 1;
            }
            loadImageFromUrl(imgURLS.get(count));
        }
    });

}


public void loadImageFromUrl(String url) {

    Picasso.with(this).load(url).placeholder(R.mipmap.ic_launcher) // optional
            .error(R.mipmap.ic_launcher) //if error
            .into(imageView, new com.squareup.picasso.Callback() {


                @Override
                public void onSuccess() {
                    // if user clicked on set wallpaper
                    // then set wallpaper
                    setBKG.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View view) {
                            Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
                            WallpaperManager myWallpaperManager = WallpaperManager
                                    .getInstance(getApplicationContext());

                            try {
                                myWallpaperManager.setBitmap(bitmap);
                                Toast.makeText(MainActivity.this, "wallpaper changed", Toast.LENGTH_LONG).show();

                            } catch (IOException e) {
                                Toast.makeText(MainActivity.this, "There was an error", Toast.LENGTH_LONG).show();

                            }

                        }
                    });

                }

                @Override
                public void onError() {

                }

            });

}


public class OnSwipeTouchListener implements OnTouchListener {

    private final GestureDetector gestureDetector;

    public OnSwipeTouchListener(Context ctx) {
        gestureDetector = new GestureDetector(ctx, new GestureListener());
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    private final class GestureListener extends SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            onSwipeRight();
                        } else {
                            onSwipeLeft();
                        }
                        result = true;
                    }
                } else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffY > 0) {
                        onSwipeBottom();
                    } else {
                        onSwipeTop();
                    }
                    result = true;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return result;
        }
    }

    public void onSwipeRight() {
    }

    public void onSwipeLeft() {
    }

    public void onSwipeTop() {
    }

    public void onSwipeBottom() {
    }
}

private class URLcollector extends AsyncTask<String, Void, ArrayList<String>> {

    private static final String TAG = "MainActivity";
    ArrayList<String> imgURLS2 = new ArrayList<>();

    // these Strings / or String are / is the parameters of the task, that can be handed over via the excecute(params) method of AsyncTask
    protected ArrayList<String> doInBackground(String... params) {

        String param1 = params[0];
        try {
            Document document = Jsoup
                    .connect("https://wubewallpapers.wordpress.com/").get();
            Elements spanElements = document.select("img");
            for (Element imgElement : spanElements) {
                imgURLS2.add(imgElement.attr("src"));
            }

        } catch (Exception e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
        // the Integer variable is used for progress
        publishProgress();

        // once the data is downloaded (for example JSON data)
        // parse the data and return it to the onPostExecute() method
        // in this example the return data is simply a long value
        // this could also be a list of your custom-objects, ...
        return imgURLS;
    }

    // the onPostexecute method receives the return type of doInBackGround()
    @Override
    protected void onPostExecute(ArrayList<String> result) {
        // do something with the result, for example display the received Data in a ListView
        // in this case, "result" would contain the "someLong" variable returned by doInBackground();
        imgURLS = imgURLS2;
    }
}
 }

05-28 20:52

2 个答案:

答案 0 :(得分:0)

这里的问题很简单 - AsyncTask.execute异步。它在一个单独的线程中启动任务,然后在任务运行之前立即返回。这就是为什么你的列表是空的并抛出IndexOutOfBoundsException。它尚未填充,因为AsyncTask尚未运行。最简单的解决方案是在执行调用后将所有内容都放在onCreate中,然后将其放在onPostExecute方法中。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageView = findViewById(R.id.imageView);
    setBKG = findViewById(R.id.setBKG);

    new URLcollector().execute(websteURL);
    // take it from here...
}

@Override
protected void onPostExecute(ArrayList<String> result) {
    // do something with the result, for example display the received Data in a ListView
    // in this case, "result" would contain the "someLong" variable returned by doInBackground();
    imgURLS = imgURLS2;
    // ...and put it here
    loadImageFromUrl(imgURLS.get(count));


    imageView.setOnTouchListener(new OnSwipeTouchListener(MainActivity.this) {
        public void onSwipeRight() {
            Toast.makeText(MainActivity.this, "right : " + imgURLS.size(), Toast.LENGTH_SHORT).show();
            if (count == imgURLS.size() - 1) {
                count = 0;
            } else {
                count++;
            }
            loadImageFromUrl(imgURLS.get(count));
        }

        public void onSwipeLeft() {
            // Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
            if (count == 0) {
                count = imgURLS.size() - 1;
            } else {
                count -= 1;
            }
            loadImageFromUrl(imgURLS.get(count));
        }
    });

}

答案 1 :(得分:0)

嗨,请查看以下几点

1.您正在尝试访问0元素:

new URLcollector()。execute(websteURL); loadImageFromUrl(imgURLS.get(计数));

但你没有把它用于imgURLS

  1. 方法 protected ArrayList doInBackground(String ... params) 返回imgURLS而不是imgURLS2