In my application i want to fetch data from multiple URLs and bind json response to respective classes, Like Gallery Url response will be bind with Gallery class.
I am able to make a call for single URL and Class, But i want to make a call for 10 times with different URLs and Class names. How can i do that?
here is my code:
String url="http://icetea09.com/blog-files/demo_json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvResult = (TextView) findViewById(R.id.tvResult);
VolleyHelper.getInstance(getApplicationContext()).addToRequestQueue(gsonRequest);
}
final GsonRequest gsonRequest = new GsonRequest(url, Gallery.class, null, new Response.Listener<Gallery>() {
#Override
public void onResponse(Gallery gallery) {
String textResult = "";
for (int i = 0; i < gallery.matches.size(); i++) {
Match Item = gallery.matches.get(i);
textResult += "URL: " + Item.url + "\n";
}
tvResult.setText(textResult);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError != null) {
Log.e("MainActivity", "" + volleyError.getMessage());
}
}
});
Please suggest me how can i make this call in for loop?
Thank you.
Here's one way of doing it:
private List<String> urls;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addUrls();
doRequests();
tvResult = (TextView) findViewById(R.id.tvResult);
VolleyHelper.getInstance(getApplicationContext()).addToRequestQueue(gsonRequest);
}
private void addUrls() {
urls = new ArrayList<String> ();
// add your urls here
urls.add("http://icetea09.com/blog-files/demo_json");
}
private void doRequests() {
for (String url : urls) {
GsonRequest gsonRequest = new GsonRequest(url, Gallery.class, null, new Response.Listener<Gallery>() {
#Override
public void onResponse(Gallery gallery) {
String textResult = "";
for (int i = 0; i < gallery.matches.size(); i++) {
Match Item = gallery.matches.get(i);
textResult += "URL: " + Item.url + "\n";
}
tvResult.setText(textResult);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError != null) {
Log.e("MainActivity", "" + volleyError.getMessage());
}
}
});
}
}
Feel free to optimize it as you want, as I'm not very familiar with Gson and initializing a new GsonRequest object per iteration is not recommendable for a big ammount of urls.
The idea behing this code is to encapsulate your GsonRequest inside a for loop. All your urls are given inside an ArrayList (add them in the addUrls() method!), and a new request is performed for every element in the Array.
To perform this loop with multiple classes, you should create a supper-class and make inherit all your classes from it, and in the loop call this supper-class.
Related
I want to execute taking data from JSON as shown below. But when
Toast.makeText(this, MangIDtrailer.size () + "..... check size of Array IDtrailer .....", Toast.LENGTH_LONG).show();
it returns 0.
I don't know what the cause is.
public class Main2Activity extends AppCompatActivity {
ListView Listmovie;
ArrayList<String> MangIDtrailer;
public static ArrayList<InfoMovie> inforMovieArrayList;
AdapterMovie adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
String url1 ="http://the....ying";
inforMovieArrayList = new ArrayList<>();
MangIDtrailer = new ArrayList<>();
MangIDtrailer = GetIDMovie(url1);
inforMovieArrayList = DataMovie(MangIDtrailer);
Listmovie = (ListView) findViewById(R.id.ListMovie);
adapter = new AdapterMovie(this, R.layout.movielist, inforMovieArrayList);
Listmovie.setAdapter(adapter);
Listmovie.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(Main2Activity.this,Review_Movie.class);
intent.putExtra("IDmovie",i);
//Toast.makeText(MainActivity.this, ""+i, Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
}
public ArrayList<String> GetIDMovie (String Url) {
final ArrayList<String> ArrayID = new ArrayList<>();
final RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, Url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String IDTrailer;
JSONArray jsonArrayFreeMovies = response.getJSONArray("FreeMovies");
for (int i=0; i < jsonArrayFreeMovies.length(); i++) {
JSONObject jsonObjectFreeMovies = jsonArrayFreeMovies.getJSONObject(i);
IDTrailer = jsonObjectFreeMovies.getString("trailer_id");
ArrayID.add(IDTrailer);
Toast.makeText(Main2Activity.this, i+"************", Toast.LENGTH_SHORT).show();
}
Toast.makeText(Main2Activity.this, MangIDtrailer.get(2)+"check Data ", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(jsonObjectRequest);
queue.cancelAll(jsonObjectRequest);
return ArrayID;
}
public ArrayList <InfoMovie> DataMovie (ArrayList<String> MangIDtrailer) {
final ArrayList<InfoMovie> inforMovieArray = new ArrayList<>();
final String linkDetail = "http://tk/api/trailers/movDetail?trailer_id=";
final RequestQueue queue2 = Volley.newRequestQueue(this);
//////////////Check that MangIDtrailer.size () has no data////////////////////////////////////
Toast.makeText(this, MangIDtrailer.size()+".....check size of Array IDtrailer .....",Toast.LENGTH_LONG).show();
for (int i=0; i<MangIDtrailer.size(); i++) {
JsonObjectRequest jsonObjectRequest2 = new JsonObjectRequest(Request.Method.GET, linkDetail + MangIDtrailer.get(i) + "&test_fullVer=1", null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String linkposter, linkbackdrop, namemovie, overviewmovie, Release_date, Urltrailer;
Float Vote_average;
String linkHot = "https://image.tmdb.org/t/p/w500/";
JSONObject jsonObjectInfo = null, jsonObjectMore = null;
JSONObject jsonopFreeMovies1 = response.getJSONObject("FreeMovies");
if (jsonopFreeMovies1.has("FreeMovies")) {
//Toast.makeText(MainActivity.this, "Cos ", Toast.LENGTH_SHORT).show();
JSONObject jsonObjectFreeMovies2 = jsonopFreeMovies1.getJSONObject("FreeMovies");
jsonObjectInfo = jsonObjectFreeMovies2.getJSONObject("Info");
jsonObjectMore = jsonObjectFreeMovies2.getJSONObject("More");
} else {
//Toast.makeText(MainActivity.this, "Khoong cos", Toast.LENGTH_SHORT).show();
jsonObjectInfo = jsonopFreeMovies1.getJSONObject("Info");
jsonObjectMore = jsonopFreeMovies1.getJSONObject("More");
}
namemovie = jsonObjectInfo.getString("title");
Urltrailer = jsonObjectInfo.getString("trailer_urls");
linkposter = linkHot + jsonObjectInfo.getString("thumbnail");
overviewmovie = jsonObjectMore.getString("overview");
linkbackdrop = linkHot + jsonObjectMore.getString("backdrop_path");
Release_date = jsonObjectMore.getString("release_date");
Vote_average = Float.valueOf(jsonObjectMore.getLong("vote_average"));
inforMovieArray.add(new InfoMovie(namemovie, overviewmovie, linkposter, linkbackdrop, Vote_average, Release_date));
Toast.makeText(Main2Activity.this,namemovie + "-" + overviewmovie + "-" + Vote_average, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Toast.makeText(Main2Activity.this, "Lỗi", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main2Activity.this, "Lỗi Try catch", Toast.LENGTH_SHORT).show();
}
});
queue2.add(jsonObjectRequest2);
}
return inforMovieArray;
}
}
As you suggested
Toast.makeText(this, MangIDtrailer.size()+".....check size of Array IDtrailer .....",Toast.LENGTH_LONG).show();
This is where you are getting size zero, which is absolutely true, because you have only initialized your array MangIDtrailer and it is an empty array. Your function GetIDMovie(url1); has a loop which populates your MangIDtrailer array which is below where you have called the toast. So your array is empty and thus its size returns zero.
One handy tip for you, you should name your functions in camelCase with first letter of your word in lowercase. GetIDMovie(url1) seems more like a class constructor. :)
EDIT:
The above solves your initial problem.
To fully solve your problem, you have to understand that Network Operations are asynchronous, meaning they will execute after sometime or they may return no value at all depending on various conditions, like network bandwidth, your server state, the parameters passed to your HTTP requests, etc.
You have two network calls in your above code; in functions: GetIDMovie() and DataMovie(). The second function requires an array of IDs which is only available if your first request is complete and returns an array of ids. So what you would want to do is, only after you get the array of ids ie. in onResponse of GetIDMovie() after the for loop, you should make a call to DataMovie().
This however is really ugly solution. I hope you will research further for better solution.
Okay, my first post because I've reached the limits of researching.
I try to run 3 requests, each with a different url inside a for loop (I've tried also with while and if) and the code runs perfectly, untiiiiil it gets to the requestqueue. Now the thing is: after the request queue I want to get the response, and only then make the for loop again, but that does not seem to be what the program wants to do, because after I add the requestqueue, the class goes back to the for loop, and continues the whole function until the end, and only in the end I get 3 followed responses, and it is pissing me off, because I want the requests one at each time. I've done many requests before, and thought I knew how to work this out, but I can't =s
Code:
public class MainActivity extends FragmentActivity {
private String totalresults, word, results, server, userAgent, quantity, urly, nome;
private int counter,limit;
EditText nome_empresa;
public TextView output;
ProgressDialog PD;
ViewPager viewPager=null;
public ArrayList half_cards, all_cards;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nome_empresa = (EditText) findViewById(R.id.nome_empresa);
output = (TextView) findViewById(R.id.output);
PD = new ProgressDialog(this);
PD.setMessage("Loading....");
PD.setCancelable(false);
//viewPager = (ViewPager) findViewById(R.id.pager);
//FragmentManager fragmentManager = getSupportFragmentManager();
//viewPager.setAdapter(new MyAdapterAlfa(fragmentManager));
}
public void vamos(View view) {
nome = nome_empresa.getText().toString();
PD.show();
googlesearch(nome, 200, 0);
ListView lv = (ListView) findViewById(R.id.custom_list_view);
lv.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, all_cards));
all_cards = get_cards(totalresults, nome);
PD.dismiss();
}
public void googlesearch(String worde, int limite, int start) {
word = worde;
results = "";
totalresults = "";
server = "www.google.com";
userAgent = "(Mozilla/5.0 (Windows; U; Windows NT 6.0;en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6";
quantity = "100";
counter = start;
limit = limite;
do_search();
}
public void do_search() {
for(int l=counter; l<=limit; l+=100){
urly = "http://" + server + "/search?num=" + quantity + "&start=" + Integer.toString(counter) + "&hl=en&meta=&q=%40\"" + word + "\"";
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest strReq = new StringRequest(Request.Method.GET, urly, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
half_cards = get_cards(response, word);
all_cards.addAll(half_cards);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: " + error.getMessage());
}
});
requestQueue.add(strReq);
}
}
public ArrayList get_cards(String ola, String ole){
myparser rawres = new myparser(ola, ole);
return rawres.cards();
}
}
Volley request is asynchronous so when response comes back loop is over some time ago. To do request queue it must be recursive - run next request call in response of previous one.
While I was searching for how to fire my own activity for links in html parsed with Jsoup, I stumbled upon LinkEnabledTextView
In the demo, it was implemented for strings but in my case, I am fetching the text from the web and displaying it in a TextView.
In the accepted answer in this question, it was applied to listitem. I followed the instructions in both links but I am having
problems applying it to my scenario.
NewsDetails class
public class NewsDetails extends AppCompatActivity implements TextLinkClickListener{
TextView newsTitle;
LinkEnabledTextView newsContent;
private String news_content;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_details);
showDialog();
newsTitle = (TextView) findViewById(R.id.dnews_title);
newsAuthorDate = (TextView) findViewById(R.id.author_date);
newsContent = (LinkEnabledTextView) findViewById(R.id.dnews_content);
check = new LinkEnabledTextView(this, null);
check.setOnTextLinkListener(this);
check.gatherLinksForText(String.valueOf(newsContent));
check.setTextColor(Color.BLUE);
check.setLinkTextColor(Color.RED);
MovementMethod movementMethod = check.getMovementMethod();
if ((movementMethod == null) || !(movementMethod instanceof LinkMovementMethod)) {
if (check.getLinksClickable()) {
check.setMovementMethod(LinkMovementMethod.getInstance());
}
}
//Skipped unecassry codes
}
private void showDialog() {
internetDialog = new AlertDialog.Builder(NewsDetails.this)
...
}
private void loadNews() {
Log.d(TAG, "loadNews called");
final ProgressBar progressBar;
progressBar = (ProgressBar) findViewById(R.id.progress_circle);
progressBar.setVisibility(View.VISIBLE);
String news_id = getIntent().getStringExtra("NewsId");
Log.d(TAG, "You clicked news id " + news_id);
StringRequest stringRequest = new StringRequest(news_id,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Log.d("Debug", response.toString());
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
parseHtml(response);
newsData = response;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
final AlertDialog.Builder sthWrongAlert = new AlertDialog.Builder(NewsDetails.this);
...
sthWrongAlert.show();
}
});
//Creating requestqueue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request queue
requestQueue.add(stringRequest);
}
private void parseHtml(String response) {
Log.d(TAG, "parsinghtml");
Document document = Jsoup.parse(response);
String news_title = document.select("h1.entry-title").first().text();
news_content = document.select("div.entry-content").first().html();
newsTitle.setText(news_title);
Spanned spanned = Html.fromHtml(news_content, new UILImageGetter(newsContent, this), null );
newsContent.setText(spanned);
//Unhiding views
newsTitle.setVisibility(View.VISIBLE);
newsContent.setVisibility(View.VISIBLE);
}
}
I have tried to pass String.valueOf(newsContent) to check.gatherLinksForText but it didn't work.
I have also tried check.gatherLinksForText(news_content) but it throws NPE.
Please what is the right parameter that I should pass check.gatherLinksForText() to make it work?
if (isConnected()) {
Event eInstance = new Event();
theEvents = eInstance.downloadEvents(eventsNightlife, getActivity());
rAdapter = new RecyclerAdapter(theEvents);
recyclerView.setAdapter(rAdapter);
progrsBar.setVisibility(View.GONE);
....
This is part of the code that runs at "onCreateView". The method downloadEvents uses Volley to download JSON data, extract it and return a list of items (theEvents). Now when my app starts, the recycler view is empty. If I go to my home screen out of the app and then run my app again, this time the data sometimes gets downloaded.
I debugged step by step, and at first launch (i mean when the app is not just resuming), theEvents is empty, so the download didn't return or manage to return anything...
Suggestions on how to execute things before the UI has been shown to the user or what actually needs to be done to approach this task better?
Also, I use a swipeRefreshLayout and at its onRefresh method I do:
public void onRefresh() {
Event eInstance = new Event();
theEvents = eInstance.downloadEvents(eventsNightlife, getActivity());
rAdapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
but it doesn't work. I also tried to
rAdapter = new RecyclerAdapter(theEvents);
rAdapter.notifyDataSetChanged();
recyclerView.swapAdapter(rAdapter, false);
still not working.
EDIT: My downloadEvents method implementing Volley:
public List<Event> downloadEvents(String urlService, Context context) {
eventsList = new ArrayList<>();
RequestQueue requestQueue = Volley.newRequestQueue(context);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
(Request.Method.GET, urlService, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
String durationStr = null;
for (int i = 0; i < response.length(); i++) {
JSONObject eventJson = response.getJSONObject(i);
String title = eventJson.getString("EventTitle");
String body = eventJson.getString("EventBody");
String date = eventJson.getString("EventDate");
String time = eventJson.getString("EventTime");
int duration = Integer.parseInt(eventJson.getString("EventDuration"));
if (duration > 60) {
durationStr = "Duration: " + duration / 60 + " h";
} else if (duration < 60) {
durationStr = "Duration: " + duration + " m";
}
String place = eventJson.getString("EventPlace");
String organ = eventJson.getString("Organization");
Event event = new Event(title, body, date, time, durationStr, place, organ);
eventsList.add(event);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY ERROR", "" + error);
}
}
);
requestQueue.add(jsonArrayRequest);
return eventsList;
}
You can use EventBus for your purpose that is a simple and truth way.
Here, i write an example for how to use EventBus with volley.
Consider that i want to download some data.
This is the class that my download methods is inside it (you can add more methods to it in the future):
Im used volley to download my data:
// Download methods is inside volley
public class MyDownloader{
public static void downloadData(){
DownloadDataEvent dlDataEvent=new DownloadDataEvent();
List<String> myResult=new ArrayList<>();
...
#Override
public void onResponse(JSONArray response) {
super.onResponse(response);
if(respone!=null){
// Do what i want with my received data
dlDataEvent.setData(response);
}
// Post my event by EventBus
EventBus.getDefault().post(dlDataEvent);
...
}
}
}
This is my event:
public class DownloadDataEvent{
private JSONArray mData;
public void setData(JSONArray data){
mData=data;
}
public JSONArray setData(){
return mData;
}
}
Now i want to use my downloadData() method inside my MainActivity:
(I called my downloadData method inside onCreate.)
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// I have to register this class for EventBus subscriber:
if(!EventBus.getDefault().isRegister(this)){
EventBus.getDefault().registerSticky(this);
}
// Call my downloadData method
if(isConnected()){
MyDownloader.downloadData();
}
}
// And for receive the data through EventBus, i have to create a
// method (subscriber) in this template:
public void onEventMainThread(DownloadDataEvent downloadDataEvent){
JSONArray result=downloadDataEvent.getData();
// Do what i want with my received data
}
}
you can create more than one subscriber every where you want to use received data.
I passed JSONArray to my DownloadDataEvent that it is not good. you can deserialize your received data and pass it to your DownloadDataEvent.
I used Volley to download data
Maybe my descriptions were confusing, but EventBus is a well-known library and is very easy to use.
I have an activity in which layout I have X checkboxes and X TextView.
Through "setText()" I am filling the TextViews with text parsed through JSON in a complex form (several values from several columns plus static text).
I would like to convert this answer in a string to be later added to an Arraylist but it turns out null (I think because of the quotation marks).
this is the average text I am parsing and "setText"ing:
public void showJSON(String response){
String One="";
String Two="";
String Three = "";
String Four = "";
try {
JSONObject jsonObject = new JSONObject(response4);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
One = collegeData.getString(Config.KEY_One);
Two = collegeData.getString(Config.KEY_Two);
Three = collegeData.getString(Config.KEY_Three);
Four = collegeData.getString(Config.KEY_Four);
} catch (JSONException e) {
e.printStackTrace();
}
textView.setText("One:\t"+One+"\nTwo:\t" +Two+ "\nThree: "+ Three+"\nFour:\t"+Four);
}
I tried newString = String.valueOf("One:\t"+One+"\nTwo:\t" +Two+ "\nThree: "+ Three+"\nFour:\t"+Four); right after the setText, but it returns a null.
With a String newString = ""; it also becomes a problem as I have quotation marks in the code as well.
It goes without saying that both String newString; and TextView textView; are declared at the beginning.
Any guess?
Complete code is as following
public class Popup1 extends Activity {
public TextView textViewResult;
public String newString;
public ArrayList<String> builder = new ArrayList<String>();
public CheckBox check;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup1);
textViewResult = (TextView) findViewById(R.id.textViewResult);
final CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkBox);
checkView(checkBox1, "holacheck", newString);
isChecked(checkBox1, "holacheck");
getData();
}
public void checkView (final CheckBox view, final String key, final String newString) {
view.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (view.isChecked()) {
KeySaver.saveShare(Popup1.this, key, view.isChecked());
builder.add((String.valueOf(newString)));
builder.add("\n");
} else {
KeySaver.removeKey(Popup1.this, key);
}
}
});
}
public void isChecked(final CheckBox view, String key){
if(view != null){
if(KeySaver.isExist(Popup1.this, key)){
view.setChecked(KeySaver.getBoolSavedShare(Popup1.this, key));
}else{
view.setChecked(false);
}
}
}
public void getData() {
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
StringRequest stringRequest = new StringRequest(Config.DATA_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Popup1.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void showJSON(String response){
String One="";
String Two="";
String Three = "";
String Four = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
One = collegeData.getString(Config.KEY_One);
Two = collegeData.getString(Config.KEY_Two);
Three = collegeData.getString(Config.KEY_Three);
Four = collegeData.getString(Config.KEY_Four);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("One:\t" + One + "\nTwo:\t" + Two + "\nThree:\t" + Three + "\nFour:\t" + Four);
newString = String.valueOf("One:"+One+"Two:" +Two+ "Three:"+ Three+"Four:"+Four);
}
}
#Override
public void finish() {
String risultato = builder.toString().replace("[", "").replace("]", "");
// Prepare data intent
Intent data = new Intent();
data.putExtra("result", risultato);
setResult(1, data );
super.finish();
}
}
newString is null the first time you access it in onCreate() in the line:
checkView(checkBox1, "holacheck", newString);
This is because your data hadn't been retrieved yet at that point.
Make checkBox1 a class field, and move the checkView() call to the end of the showJSON() method.
private CheckBox checkBox1;
...
public void onCreate(Bundle savedInstanceState) {
...
checkBox1 = (CheckBox) findViewById(R.id.checkBox);
isChecked(checkBox1, "holacheck");
getData();
}
public void showJSON(String response){
...
textViewResult.setText("One:\t" + One + "\nTwo:\t" + Two + "\nThree:\t" + Three + "\nFour:\t" + Four);
newString = String.valueOf("One:"+One+"Two:" +Two+ "Three:"+ Three+"Four:"+Four);
checkView(checkBox1, "holacheck", newString);
}