Skip to content

Instantly share code, notes, and snippets.

@MostafaAtefsaber
Last active October 21, 2018 21:51
Show Gist options
  • Save MostafaAtefsaber/ee77362e40aafc2a8f922498c896cf51 to your computer and use it in GitHub Desktop.
Save MostafaAtefsaber/ee77362e40aafc2a8f922498c896cf51 to your computer and use it in GitHub Desktop.
Android FechData
package com.example.mostafa.json;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FechData extends AsyncTask<Void, Void, Void> {
String data ="";
@Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://api.myjson.com/bins/hx610");
// create connection
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
// create input stream
InputStream inputStream = httpURLConnection.getInputStream();
// create BufferedReader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
// create string line that read line by line
String line = "";
line = bufferedReader.readLine();
Log.d("linee",line);
while ((line = bufferedReader.readLine()) != null){
Log.d("Dataa",data);
data = data + line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.data.setText(this.data);
}
}
package com.example.mostafa.json;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
public static TextView data ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data = (TextView) findViewById(R.id.TextViewData);
}
public void getData(View view){
Toast.makeText(this,"button clickd",Toast.LENGTH_SHORT).show();
FechData process = new FechData();
process.execute();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment