按下按钮时刷新json url

时间:2018-04-08 18:38:14

标签: java android json android-studio android-edittext

我发现我是如何做的,我在较早的问题中做了什么,但我想知道如何重新加载URL url = new URL("https://www.lurkinator.net/api/data?username="+typedText+"");用户按下按钮后?我有一个名为"按钮"我希望它刷新网址,因为我在最后有typedText,当用户编辑edittext时,我希望数据从api刷新

这是我的代码。以下是应用程序外观的截图,以便您有一个想法。 Photo



public class MainActivity extends AppCompatActivity {
    TextView points, username;

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

        points = (TextView) findViewById(R.id.textView8);
        username = (TextView) findViewById(R.id.textView9);
        new getData().execute();
    }



    class getData extends AsyncTask<String, String, String> {
        // get EditText by id and store it into "inputTxt"
        EditText USERNAME = (EditText) findViewById(R.id.UserSet);

        // Store EditText - Input in variable
        String typedText = USERNAME.getText().toString();
        HttpURLConnection urlConnection = null;



        @Override
        protected String doInBackground(String... args) {
            StringBuilder result = new StringBuilder();
            try {
                URL url = new URL("https://www.lurkinator.net/api/data?username="+typedText+"");

                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");

                urlConnection.setDoOutput(true);

                urlConnection.connect();

                BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));

                char[] buffer = new char[1024];

                String line;
                while ((line = br.readLine()) != null) {
                    result.append(line+"\n");
                }
                br.close();

                String jsonString = result.toString();

                System.out.println("JSON: " + jsonString);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                urlConnection.disconnect();
            }

            return result.toString();
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                JSONArray jsonArray = new JSONArray(result);
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                String t = jsonObject.getString("points");
                String u = jsonObject.getString("username");

                points.setText(t);
                username.setText(u);



            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}
&#13;
&#13;
&#13;

谢谢!

1 个答案:

答案 0 :(得分:1)

添加ok按钮单击侦听器

Button clickButton = (Button) findViewById(R.id.clickButton);
clickButton.setOnClickListener( new OnClickListener() { 
    @Override 
     public void onClick(View v) { 
        new getData().execute();
     } 
});