마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

안드로이드 Thread 관련 질문드립니다

0 추천
안녕하세요 안드로이드 진로를 잡고 공부하고있는 학생입니다.
안드로이드 <--> 웹서버 통신을 이용해 이미지 파일과 글을 읽어와 리스트뷰에 뿌려주는 앱을 포트폴리오로 만들려고 개발중에 시험으로 디비에 데이터를 2개 저장하고 테스트 해봤는데 정상적으로 구동되서 데이터를 10 개정도 넣고  돌려보니 이미지들이 자기 마음대로 바꼇다가 다시 정상적인 이미지로 돌아오고 스피너(지역)또한 동작하질않습니다 . 고수님들 도와주세요 

 코드가 짤려서 댓글에 이어서 올렷습니다 .
public class MainActivity extends AppCompatActivity {

    Handler handler = new Handler();
    Spinner location1, location2;
    Button search;
    ArrayList<String> arrayList, arrayList2;
    ArrayAdapter<String> arrayAdapter, arrayAdapter2;
    TextView test;
    public String location;
    public String location2_idr;
    public String clickhtml="http://211.226.100.190:8080/db/nemotest.jsp";
    public String type;
    public  String[] address;
    public  String[] name;
    public String threadClose;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        locationThread locationThread = new locationThread();
        locationThread.start();

        myThread thread = new myThread();
        thread.start();
        search=(Button)findViewById(R.id.serach);
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(type !=null) {
                    clickhtml = "http://211.226.100.190:8080/db/nemotest.jsp?location2_id=" + location2_idr+"&type="+type;
                    Toast.makeText(getApplicationContext(),clickhtml,Toast.LENGTH_LONG).show();
                    myThread thread = new myThread();
                    thread.start();

                }
                else
                {
                    clickhtml = "http://211.226.100.190:8080/db/nemotest.jsp?location2_id=" + location2_idr;
                    Toast.makeText(getApplicationContext(),clickhtml,Toast.LENGTH_LONG).show();
                    myThread thread = new myThread();
                    thread.start();

                }
            }
        });


    }
    
kane9529 (1,110 포인트) 님이 2019년 5월 27일 질문
kane9529님이 2019년 5월 27일 수정
class myThread extends Thread {
        public void run() {
            Document doc = null;
            //String html = "http://211.226.100.190:8080/db/nemotest.jsp";
            try {
                URL url = new URL(clickhtml);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                      doc = Jsoup.connect(clickhtml).get();

                    Elements img = doc.select("img");
                    Elements atag=doc.select("h1");
                    final String[] asrc = new String[img.size()];
                    String[] imgsrc = new String[img.size()];
                    address=new String[atag.size()/2];
                     name=new String[atag.size()/2];
                    final ListView lv = (ListView) findViewById(R.id.listview);
                    final ArrayList<Story> al = new ArrayList<Story>();
                    al.clear();


                    int count=0;
                    for(int j=0; j<atag.size()/2; j++)
                    {
                        address[j]=doc.select("h1").get(count).getElementsByTag("h1").html();

                        count++;
                        name[j]=doc.select("h1").get(count).getElementsByTag("h1").html();
                        count++;

                    }

                    for (int i = 0; i < img.size(); i++) {
                        imgsrc[i] = doc.select("a").get(i).getElementsByTag("img").attr("src");
                        asrc[i] = doc.select("a").get(i).getElementsByTag("a").attr("href");
                        al.add(new Story(name[i], address[i], imgsrc[i]));

                    }
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            MyAdapter adapter = new MyAdapter(
                                    MainActivity.this,
                                    R.layout.list_item,
                                    al);

                            lv.setAdapter(adapter);

                        }
                    });
                    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            Toast.makeText(getApplicationContext(), asrc[position], Toast.LENGTH_SHORT).show();

                            String DetailHttp = asrc[position];
                            Intent intent = new Intent(MainActivity.this, Detail.class);
                            intent.putExtra("DetailHttp", DetailHttp);
                            startActivity(intent);

                        }
                    });

                }


            } catch (IOException e) {
                e.printStackTrace();
            }

        }


    }


   
class MyAdapter extends BaseAdapter {
        Context context;
        int layout;
        ArrayList<Story> al;
        LayoutInflater inf;

        public MyAdapter(Context context, int layout, ArrayList<Story> al) {
            this.context = context;
            this.layout = layout;
            this.al = al;
            this.inf = (LayoutInflater) context.getSystemService
                    (Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return al.size();
        }

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

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

        @Override
        public View getView(int position, View v, ViewGroup parent) {
            if (v == null)
                v = inf.inflate(layout, null);

            TextView tv1 = (TextView) v.findViewById(R.id.text1);
            TextView tv2 = (TextView) v.findViewById(R.id.text2);
            ImageView iv = (ImageView) v.findViewById(R.id.image);

            Story s = al.get(position);
            tv1.setText(s.date);
            tv2.setText(s.message);
            OpenHttpConnection opHttpCon = new OpenHttpConnection();
            opHttpCon.execute(iv, "http://211.226.100.190:8080/db/" + s.img);

            return v;
        }
    }

    public class Story {
        String date = "";
        String message = "";
        String img = "";

        public Story(String date, String message, String img) {
            this.date = date;
            this.message = message;
            this.img = img;
        }

        public Story() {
        }
    }


    public class OpenHttpConnection extends AsyncTask<Object, Void, Bitmap> {

        private ImageView bmImage;

        @Override
        protected Bitmap doInBackground(Object... params) {
            Bitmap mBitmap = null;
            bmImage = (ImageView) params[0];
            String url = (String) params[1];
            InputStream in = null;
            try {
                in = new java.net.URL(url).openStream();
                mBitmap = BitmapFactory.decodeStream(in);
                in.close();

            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return mBitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bm) {
            super.onPostExecute(bm);
            bmImage.setImageBitmap(bm);
        }
    }
public class locationThread extends Thread {
        public void run() {
            Document document;
            String html = "http://211.226.100.190/db/location1.jsp";

            try {
                document = Jsoup.connect(html).get();
                Elements A = document.select("a");
                final String[] location1_id = new String[A.size() / 2];
                String[] location1_name = new String[A.size() / 2];
                arrayList = new ArrayList<>();
                for (int i = 0; i < A.size() / 2; i++) {
                    location1_id[i] = document.select("a").get(i*2).html();

                }
                for (int j = 0; j < A.size() / 2; j++) {
                    location1_name[j] = document.select("a").get((j * 2) + 1).html();
                    arrayList.add(location1_name[j]);

                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        location1 = (Spinner) findViewById(R.id.location1);
                        arrayAdapter = new ArrayAdapter<>(getApplicationContext(),
                                android.R.layout.simple_spinner_dropdown_item,
                                arrayList);
                        location1.setAdapter(arrayAdapter);
                        location1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

                                location = location1_id[i];
                                location2Thread location2Thread=new location2Thread();
                                location2Thread.start();
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {
                            }
                        });
                    }
                });


            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public class location2Thread extends Thread {
        public void run() {
            String html = "http://211.226.100.190:8080/db/location2.jsp?location1_id=" + location;
            Document document;
            try {
                document = Jsoup.connect(html).get();
                Elements ac = document.select("a");
                final String[] location2_id = new String[ac.size() / 2];
                final String[] location2_name = new String[ac.size() / 2];
                arrayList2 = new ArrayList<>();
                for (int i = 0; i < ac.size() / 2; i++) {
                    location2_id[i] = document.select("a").get(i*2).html();

                }
                for (int j = 0; j < ac.size() / 2; j++) {
                    location2_name[j] = document.select("a").get((j * 2) + 1).html();

                    arrayList2.add(location2_name[j]);

                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {

                        location2 = (Spinner) findViewById(R.id.location2);
                        arrayAdapter2 = new ArrayAdapter<>(getApplicationContext(),
                                android.R.layout.simple_spinner_dropdown_item,
                                arrayList2);
                        location2.setAdapter(arrayAdapter2);
                        location2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                location2_idr=location2_id[i];

                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {
                            }
                        });
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

}

답변 달기

· 글에 소스 코드 보기 좋게 넣는 법
· 질문에 대해 추가적인 질문이나 의견이 있으면 답변이 아니라 댓글로 달아주시기 바랍니다.
표시할 이름 (옵션):
개인정보: 당신의 이메일은 이 알림을 보내는데만 사용됩니다.
스팸 차단 검사:
스팸 검사를 다시 받지 않으려면 로그인하거나 혹은 가입 하세요.
...