Android
Android [파파고번역앱] 라디오 버튼, Volley
leopard4
2023. 2. 13. 12:19
매인액티비티
package com.leopard4.translateapp;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.leopard4.translateapp.adapter.TranslateAdapter;
import com.leopard4.translateapp.config.Config;
import com.leopard4.translateapp.model.History;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton radioBtn1;
RadioButton radioBtn2;
RadioButton radioBtn3;
RadioButton radioBtn4;
Button button;
TextView txtResult;
EditText editText;
final String URL = "https://openapi.naver.com/v1/papago/n2mt";
ArrayList<History> historyList = new ArrayList<>();
String text;
String result;
String target;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("번역기");
radioGroup = findViewById(R.id.radioGroup);
radioBtn1 = findViewById(R.id.radioBtn1);
radioBtn2 = findViewById(R.id.radioBtn2);
radioBtn3 = findViewById(R.id.radioBtn3);
radioBtn4 = findViewById(R.id.radioBtn4);
button = findViewById(R.id.button);
txtResult = findViewById(R.id.txtResult);
editText = findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 1. 에디터 텍스트에서 유저가 작성한 글을 가져온다.
text = editText.getText().toString().trim();
if (text.isEmpty()) {
editText.setError("Please enter text");
return;
}
// 2. 어떤 언어로 번역할지를 라디오버튼 정보 가져온다.
int selectedId = radioGroup.getCheckedRadioButtonId();
if (selectedId == R.id.radioBtn1) {
target = "en";
} else if (selectedId == R.id.radioBtn2) {
target = "zh-CN";
} else if (selectedId == R.id.radioBtn3) {
target = "zh-TW";
} else if (selectedId == R.id.radioBtn4) {
target = "th";
} else {
editText.setError("Please select language");
return;
}
// 3. 파파고 API 호출
String source = "ko";
JSONObject body = new JSONObject();
try {
body.put("source", source);
body.put("target", target);
body.put("text", text);
} catch (JSONException e) {
throw new RuntimeException(e);
}
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.POST,
URL,
body,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i("PAPAGO_APP", response.toString());
// 4. 호출결과를 화면에 보여준다.
try {
result = response.getJSONObject("message").getJSONObject("result").getString("translatedText");
txtResult.setText(result);
// 히스토리 객체를 생성한다
History history = new History(text, result, target);
// 어레이 리스트에 넣어준다.
historyList.add(0, history);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("PAPAGO_APP", error.toString());
}
}
){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("X-Naver-Client-Id", Config.NAVER_CLIENT_ID);
headers.put("X-Naver-Client-Secret", Config.NAVER_CLIENT_SECRET);
return headers;
}
};
queue.add(request);
}
});
}
// 액션바의 메뉴는, 전용 함수가 있다.
// 이 함수를 오버라이딩 해야 한다.
@Override
public boolean onCreateOptionsMenu(@NonNull Menu menu) {
// 액션바에 메뉴가 나오도록 설정한다.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// 액션바의 메뉴를 탭했을때, 실행되는 함수가 있다.
// 이 함수를 오버라이딩 해야 한다.
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
// 메뉴의 아이디를 확인해서, 각각의 메뉴를 구분한다.
int itemId = item.getItemId();
if(itemId == R.id.menu_history){
Intent intent = new Intent(this, HistoryActivity.class);
intent.putExtra("historyList", historyList);
startActivity(intent);
}
return MainActivity.super.onOptionsItemSelected(item);
}
}
히스토리 액티비티
package com.leopard4.translateapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import com.leopard4.translateapp.adapter.TranslateAdapter;
import com.leopard4.translateapp.model.History;
import java.util.ArrayList;
public class HistoryActivity extends AppCompatActivity {
TranslateAdapter adapter;
RecyclerView recyclerView;
ArrayList<History> historyList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(HistoryActivity.this));
historyList = (ArrayList<History>) getIntent().getSerializableExtra("historyList");
adapter = new TranslateAdapter(HistoryActivity.this, historyList);
recyclerView.setAdapter(adapter);
}
}
히스토리 클래스
package com.leopard4.translateapp.model;
import java.io.Serializable;
public class History implements Serializable {
public String text;
public String result;
public String target;
public History() {
}
public History(String text, String result, String target) {
this.text = text;
this.result = result;
if (target.equals("en")) {
this.target = "영어";
} else if (target.equals("ko")) {
this.target = "한국어";
} else if (target.equals("zh-CN")) {
this.target = "중국어";
} else if (target.equals("zh-TW")) {
this.target = "중국어";
} else if (target.equals("th")) {
this.target = "태국어";
}
}
}
Config
package com.leopard4.translateapp.config;
public class Config {
public static final String NAVER_CLIENT_ID = "개인키";
public static final String NAVER_CLIENT_SECRET = "개인키";
}
adapter
package com.leopard4.translateapp.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.leopard4.translateapp.R;
import com.leopard4.translateapp.model.History;
import java.util.ArrayList;
public class TranslateAdapter extends RecyclerView.Adapter<TranslateAdapter.ViewHolder>{
Context context;
ArrayList<History> historyList;
public TranslateAdapter(Context context, ArrayList<History> historyList) {
this.context = context;
this.historyList = historyList;
}
@NonNull
@Override
public TranslateAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.history_row, parent, false);
return new TranslateAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull TranslateAdapter.ViewHolder holder, int position) {
History history = historyList.get(position);
holder.txtText.setText(history.text);
holder.txtResult.setText(history.result);
holder.txtTarget.setText(history.target);
}
@Override
public int getItemCount() {
return historyList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView txtText;
TextView txtResult;
TextView txtTarget;
public ViewHolder(@NonNull View parent) {
super(parent);
txtText = parent.findViewById(R.id.txtText);
txtResult = parent.findViewById(R.id.txtResult);
txtTarget = parent.findViewById(R.id.txtTarget);
}
}
}