Skip to content

Instantly share code, notes, and snippets.

@anta40
Created November 26, 2019 07:07
Show Gist options
  • Save anta40/89a0e4ffb9f6e54447a7673b16a63dc1 to your computer and use it in GitHub Desktop.
Save anta40/89a0e4ffb9f6e54447a7673b16a63dc1 to your computer and use it in GitHub Desktop.
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class ReadSuratActivity extends AppCompatActivity {
EditText edit_text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit_text = (EditText) findViewById(R.id.edit_text);
ReadSuratTask task = new ReadSuratTask();
task.execute("");
}
class ReadSuratTask extends AsyncTask<String, Void, String> {
private String responseServer;
public ReadSuratTask(){
}
@Override
protected void onPreExecute() {
super.onPreExecute();
responseServer = "";
}
@Override
protected String doInBackground(String... strings) {
OkHttpClient httpClient = new OkHttpClient();
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("api.banghasan.com")
.addPathSegments("quran/format/json/surat")
.build();
Request httpRequest = new Request.Builder()
.url(url)
.method("GET", null)
.build();
Response httpResponse = null;
try {
httpResponse = httpClient.newCall(httpRequest).execute();
}
catch (IOException ioe){
ioe.printStackTrace();
}
try {
if (httpResponse != null){
responseServer = httpResponse.body().string();
if (responseServer.isEmpty()){
Toast.makeText(getApplicationContext() ,"Response is empty", Toast.LENGTH_SHORT).show();
}
}
}
catch (IOException ioe){
ioe.printStackTrace();
}
return responseServer;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject bigJSONObject = new JSONObject(s);
JSONArray hasilArray = bigJSONObject.getJSONArray("hasil");
int len = hasilArray.length();
for (int x = 0; x < len; x++){
JSONObject obj = hasilArray.getJSONObject(x);
edit_text.append("Asma: "+obj.getString("asma"));
edit_text.append("\n");
}
}
catch (JSONException je){
Toast.makeText(getApplicationContext(), je.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment