I was learning how to make an api call in android. This is my fragment. I have uploaded this json file in myjson.com. From my fragment class, I tried to hit the api. I believe the response should return the data inside the json object to my log.
public class TableFragment extends android.support.v4.app.Fragment {
public TableFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_table, container, false);
Button api_btn = (Button)rootView.findViewById(R.id.enter_button);
api_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
URL url = new URL("https://api.myjson.com/bins/n80yl");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
Log.d("tagg", "onClick: "+stringBuilder);
}catch (Exception e)
{
Log.d("tagg", "onClick:exception1 "+e);
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.d("tagg", "doInBackground:exception2 "+e);
}
}
});
return rootView;
}
}
i have given the internet permission in manifest.
Is this the correct way so that i can learn the api mechanism in android. thanks in advance