Android

될 때까지 안드로이드 정리 (오준석의 생존코딩) 6

 

  1. ActionSendExam
  2. FragmentExam
  3. HttpNetworkExam

 

 


 

 1. ActionSendExam

 

<EditText
    android:id="@+id/message_edit"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="메시지" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="sendMessage"
    android:text="전달하기" />

 

public void sendMessage(View view) {
    EditText messageEditText = (EditText) findViewById(R.id.message_edit);

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_TEXT, messageEditText.getText().toString());

    // 처리할 수 있는 액티비티가 있으면 그 액티비티를 실행하라
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

 


 

 2. FragmentExam

 

public class ColorFragment extends Fragment {
    private int mColor = Color.BLUE;
    private TextView mHelloTextView;

    public ColorFragment() {
        // Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_color, container, false);
        mHelloTextView = view.findViewById(R.id.hello_text);
        mHelloTextView.setBackgroundColor(mColor);
        return view;
    }

    public void setColor(int color) {
        // 텍스트 뷰의 배경색을 변경
        mColor = color;
        if (mHelloTextView != null) {
            mHelloTextView.setBackgroundColor(mColor);
        }
    }
}

 

 

public class MainActivity extends AppCompatActivity {

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

        // 프래그먼트 조작을 위해 프래그먼트 매니저를 얻음
        FragmentManager fragmentManager = getSupportFragmentManager();
        // ColorFragment를 findFragmentById()로 얻음
        ColorFragment colorFragment = (ColorFragment) fragmentManager.findFragmentById
                (R.id.color_fragment);
        // 프래그먼트의 색상 변경
        colorFragment.setColor(Color.BLUE);

    }

    public void change(View view) {
        ColorFragment fragment = new ColorFragment();

        int red = new Random().nextInt(256);
        int green = new Random().nextInt(256);
        int blue = new Random().nextInt(256);

        fragment.setColor(Color.rgb(red, green, blue));

        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, fragment)
                .commit();
    }
}

 

fragment_color.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.fragmentexam.ColorFragment">

    <TextView
        android:id="@+id/hello_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Hello blank fragment" />

</FrameLayout>

 

activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.fragmentexam.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <fragment
            android:id="@+id/color_fragment"
            android:name="com.myhome.therestexam.ColorFragment"
            android:layout_width="match_parent"
            android:layout_height="100dp" />
    </FrameLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="change"
        android:text="교체" />
</LinearLayout>

 

 


 

 3. HttpNetworkExam

 

activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:listitem="@layout/item_weather" />

</LinearLayout>

 

 

item_weather.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/country_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="국가" />

    <TextView
        android:id="@+id/weather_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="날씨" />

    <TextView
        android:id="@+id/temperature_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="기온" />

</LinearLayout>

 

 

public class Weather {
    private String country;
    private String weather;
    private String temperature;

    public Weather(String country, String weather, String temperature) {
        this.country = country;
        this.weather = weather;
        this.temperature = temperature;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getTemperature() {
        return temperature;
    }

    public void setTemperature(String temperature) {
        this.temperature = temperature;
    }

    public String getWeather() {
        return weather;
    }

    public void setWeather(String weather) {
        this.weather = weather;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("Weather{");
        sb.append("country='").append(country).append('\'');
        sb.append(", weather='").append(weather).append('\'');
        sb.append(", temperature='").append(temperature).append('\'');
        sb.append('}');
        return sb.toString();
    }
}

 

 

public class WeatherAdapter extends BaseAdapter {
    private final List<Weather> mList;

    public WeatherAdapter(List<Weather> list) {
        mList = list;
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_weather, parent, false);

            holder = new ViewHolder();
            holder.country = convertView.findViewById(R.id.country_text);
            holder.weather = convertView.findViewById(R.id.weather_text);
            holder.temperature = convertView.findViewById(R.id.temperature_text);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Weather weather = (Weather) getItem(position);
        holder.country.setText(weather.getCountry());
        holder.weather.setText(weather.getWeather());
        holder.temperature.setText(weather.getTemperature());

        return convertView;
    }

    // 뷰 홀더 패턴
    static class ViewHolder {
        TextView country;
        TextView weather;
        TextView temperature;
    }
}

 

 

public class MainActivity extends AppCompatActivity {

    private ListView mListView;

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

        mListView = findViewById(R.id.list_view);

        // 소스를 확인하고 싶은 사이트 주소
        new HttpAsyncTask().execute("https://goo.gl/eIXu9l");
    }

    private class HttpAsyncTask extends AsyncTask<String, Void, List<Weather>> {

        @Override
        protected List<Weather> doInBackground(String... params) {
            String result = null;

            String strUrl = params[0];

            try {
                // URL 객체 생성
                URL url = new URL(strUrl);
                // URL을 연결한 객체 생성
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");     // GET 방식 통신
                // connection.setDoOutput(true);           // 쓰기 모드 (true로 하면 405 에러남)
                connection.setDoInput(true);            // 읽기 모드
                connection.setUseCaches(false);         // 캐시 사용
                connection.setDefaultUseCaches(false);

                // 입력 스트림 열기
                InputStream inputStream = connection.getInputStream();

                // 문자열 저장 객체
                StringBuilder builder = new StringBuilder();
                // UTF-8 방식으로 입력받은 스트림을 읽어들이는 버퍼 객체
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream, "UTF-8"));

                // 한 줄씩 문자열을 읽어들이기
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line + "\n");
                }

                // 결과
                result = builder.toString();

            } catch (MalformedURLException e) {
                // 에러 처리
                e.printStackTrace();
            } catch (IOException e) {
                // 에러 처리
                e.printStackTrace();
            }

            List<Weather> weatherList = new ArrayList<>();
            try {
                JSONArray jsonArray = new JSONArray(result);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String country = jsonObject.getString("country");
                    String weather = jsonObject.getString("weather");
                    String temperature = jsonObject.getString("temperature");
                    Weather w = new Weather(country, weather, temperature);
                    weatherList.add(w);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return weatherList;
        }

        @Override
        protected void onPostExecute(List<Weather> weatherList) {
            super.onPostExecute(weatherList);

            if (weatherList != null) {
                Log.d("HttpAsyncTask", weatherList.toString());
                WeatherAdapter adapter = new WeatherAdapter(weatherList);
                mListView.setAdapter(adapter);
            }
        }
    }
}

 

 

 

 

 


 

 

될 때까지 안드로이드 (오준석의 생존코딩) 유튜브 강의
https://www.youtube.com/watch?v=euTtMnN-TgI&list=PLxTmPHxRH3VWTd-8KB67Itegihkl4SVKe&index=2

 

될 때까지 안드로이드 (오준석의 생존코딩) 깃헙
https://github.com/junsuk5/android-first-book

 

될 때까지 안드로이드 소스 다운로드
android-first-book-master.zip

 

 

 

 

 

 

 

 

 

 

Related posts

Leave a Comment