Created
January 18, 2016 13:53
-
-
Save abidibo/d10107ff68ba38766b40 to your computer and use it in GitHub Desktop.
Fetch json from main activity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.torinometeo.tmforecast; | |
import android.content.Context; | |
import android.net.ConnectivityManager; | |
import android.net.NetworkInfo; | |
import android.os.AsyncTask; | |
import android.support.v7.app.AppCompatActivity; | |
import android.os.Bundle; | |
import android.widget.EditText; | |
import java.io.BufferedInputStream; | |
import java.io.BufferedReader; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.net.HttpURLConnection; | |
import java.net.URL; | |
public class MainActivity extends AppCompatActivity { | |
EditText etResponse; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
ConnectivityManager connMgr = (ConnectivityManager) | |
getSystemService(Context.CONNECTIVITY_SERVICE); | |
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); | |
if (networkInfo != null && networkInfo.isConnected()) { | |
setContentView(R.layout.activity_main); | |
etResponse = (EditText) findViewById(R.id.etResponse); | |
// call AsynTask to perform network operation on separate thread | |
new GetData().execute(); | |
} else { | |
setContentView(R.layout.activity_main_no_connection); | |
} | |
} | |
public class GetData extends AsyncTask<String, String, String> { | |
HttpURLConnection urlConnection; | |
@Override | |
protected String doInBackground(String... args) { | |
StringBuilder result = new StringBuilder(); | |
try { | |
URL url = new URL("http://new.torinometeo.org/api/v1/forecast/get-last/"); | |
urlConnection = (HttpURLConnection) url.openConnection(); | |
InputStream in = new BufferedInputStream(urlConnection.getInputStream()); | |
BufferedReader reader = new BufferedReader(new InputStreamReader(in)); | |
String line; | |
while ((line = reader.readLine()) != null) { | |
result.append(line); | |
} | |
}catch( Exception e) { | |
e.printStackTrace(); | |
} | |
finally { | |
urlConnection.disconnect(); | |
} | |
return result.toString(); | |
} | |
@Override | |
protected void onPostExecute(String result) { | |
super.onPostExecute(result); | |
//Do anything with response.. | |
etResponse.setText(result); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment