안녕하세요. 지난번에도 한번 문의 드렸었는데
도저히 답이 안나와서 다시한번 문의 드립니다.
모 게임 개발자센터에서 api키를 발급받아 json형식의 조회결과를
data변수에 받은 후
파싱하여 textview로 보여주는걸 구현하고자 합니다.
정보를 가져와서 textview에 보여주는건 완성하였지만, 검색결과가 없을시 아래처럼 toast 메시지를 띄워서 알려주려고 합니다.
구글링을 해보니 thread 에서 toast를 실행시키기 위해서는 runOnUiThread로 구현해야 한다고 하여
94행에 아래와 같이 코드를 작성하였는데..
검색은되지만 조회결과가 없을땐 여전히 토스트 메시지가 나타나지 않습니다..
runOnUiThread(new Runnable() {
public void run(){
if (data == null){
Toast noCoach = Toast.makeText(MainActivity.this, "존재하지 않는 이름입니다", Toast.LENGTH_LONG);
noCoach.show();
}
}
}
고수님들의 많은 가르침 기다리겠습니다.
감사합니다.
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.net.Network;
import android.net.http.HttpResponseCache;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
TextView text1;
EditText text2;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text1 = (TextView) findViewById(R.id.textView);
text2 = (EditText) findViewById(R.id.editTextTextPersonName);
button = (Button) findViewById(R.id.button);
}
public void btnMethod(View view) {
NetworkThread thread = new NetworkThread();
thread.start();
}
class NetworkThread extends Thread{
String data;
@Override
public void run() {
try{
String coach = text2.getText().toString();
String key = "API 키 값 입력";
String site = "URL 입력"+coach;
URL url = new URL(site);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.addRequestProperty("Authorization", key);
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is,"UTF-8");
BufferedReader br = new BufferedReader(isr);
String str = null;
StringBuffer buf = new StringBuffer();
do{
str = br.readLine();
if(str != null){
buf.append(str);
}
} while(str != null);
data = buf.toString();
runOnUiThread(new Runnable() {
@Override
public void run() {
text1.setText("");
}
});
JSONObject obj = new JSONObject(data);
String accessId = obj.getString("accessId");
String nickname = obj.getString("nickname");
int level = obj.getInt("level");
runOnUiThread(new Runnable() {
@Override
public void run() {
if (data == null){
Toast noCoach = Toast.makeText(MainActivity.this, "존재하지 않는 이름입니다", Toast.LENGTH_LONG);
noCoach.show();
}
text1.append("accessId : " + accessId + "\n");
text1.append("nickname : " + nickname + "\n");
text1.append("level : " + level + "\n\n");
}
});
}catch(Exception e){
e.printStackTrace();
}
}
}
}