-8

Just as a practicing exercise i'm trying to make an app that fetches a JSON from a URL.

I found the following code in other thread here in stackoverflow and it works just fine. My problem is that the URL is hardcoded, and i need it to be an input by the user. What should i change/add?

public class MainActivity extends AppCompatActivity {

    Button btnHit;
    TextView txtJson;
    ProgressDialog pd;

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

        btnHit = (Button) findViewById(R.id.btnHit);
        txtJson = (TextView) findViewById(R.id.tvJsonItem);

        btnHit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new JsonTask().execute("Url address here");
            }
        });
    }

    private class JsonTask extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
        super.onPreExecute();

        pd = new ProgressDialog(MainActivity.this);
        pd.setMessage("Please wait");
        pd.setCancelable(false);
        pd.show();
    }

    protected String doInBackground(String... params) {

        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line+"\n");
                Log.d("Response: ", "> " + line);   //here u ll get whole response..... :-) 
            }

            return buffer.toString();


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (pd.isShowing()){
            pd.dismiss();
        }
        txtJson.setText(result);
    }
}
}

This is the thread where i got that code from:

Get JSON Data from URL Using Android?

Armitage
  • 21
  • 1
  • 6
  • Try volley instead of this . It can help you out better. – Sachin Bahukhandi Jul 11 '17 at 10:21
  • Do you mean that you want the user to input the url instead of a hard coded url? – SripadRaj Jul 11 '17 at 10:22
  • 1
    *Can someone help me?* is not a valid question on StackOverflow ... anyway what is stopping you from adding EditText ? – Selvin Jul 11 '17 at 10:22
  • In UI before that button take one EditText & write validation on button click if it is URL then you can continue or else you show toast or alert user to enter URL – Srihari Jul 11 '17 at 10:24
  • @SachinBahukhandi i have no idea what volley is, i guess it's an external library. I'll have a look. – Armitage Jul 11 '17 at 10:34
  • @SripadRaj yes, that's exactly what i need. – Armitage Jul 11 '17 at 10:34
  • @Selvin I'm sorry, as i said i'm a total noob in android, i just wanted some help introducing a change to a code i didn't make and i'm trying to understand. As for your question, nothing stops me, i'm just a little confused since i'm not entirely sure what to touch. – Armitage Jul 11 '17 at 10:34
  • @Srihari I'm not sure if i follow you, but i'll try. Thanks for the replies, guys. – Armitage Jul 11 '17 at 10:34

2 Answers2

0

Create a constructor in your async Task

private class JSONTask extends AsyncTask<String, String, String> {
String url;
public JSONTask(String url){
this.url=url;
}

use the url string in place of params[0]

And wherever you call your async task do it like this

new JSONTask(textView.getText()).execute()

This should solve it.

Else you can directly use the do in background variable params.

Joey Pinto
  • 1,735
  • 1
  • 18
  • 34
  • This kinda worked. What i ended up doing was creating an `EditText` and then, in the line you said used `new JsonTask().execute(editTextUrl.getText().toString());` Thanks! – Armitage Jul 11 '17 at 15:01
0

So the problem is that you are using a TextView. TextView does not recieve inputs.

EditText does.

Make these Changes:

TextView txtJson;

In your OnCreate change this:

txtJson = (EditText) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new JsonTask().execute(txtJson.getText());
        }
});

Now in your xml file change the Button to EditText.

Hope this helps.

Community
  • 1
  • 1
Sachin Bahukhandi
  • 2,378
  • 20
  • 29