Current value of EditText not being passed to a function from onCreate() - android

I am building an android app that displays the COVID19 statistics for India, I am getting the stats in JSON format from https://api.covid19india.org/data.json , this API contains data of individual states too,
Below is the snip of Json array(contains json objects representing each state) that i am requesting
as of Now i am displaying the entire data ( all states ) at a time on my screen, However i want to give the state name as the input and display the stats of only that state For eg. in the below image in place of sample i want to write a state name and the stats of that state must be displayed on click of the button.
Here is the code of mainActivity.java, I am using Volley Library for fetching data from API
public class MainActivity extends AppCompatActivity {
private TextView result;
private RequestQueue mq;
public String value;
int flag = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = findViewById(R.id.textView4);
Button parse = findViewById(R.id.button);
mq = Volley.newRequestQueue(this);
EditText text = (EditText)findViewById(R.id.state_ip);
value = text.getText().toString();
parse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
jsonParse(value);
**//How do i pass 'value' i.e the state name entered by user to jsonParse**
}
});
}
private void jsonParse(final String value) {
Log.d("val_state",value);
String url = "https://api.covid19india.org/data.json";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("statewise");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject st = jsonArray.getJSONObject(i);
String statename = st.getString("state");
String active = st.getString("active");
String confirmed = st.getString("confirmed");
String deaths = st.getString("deaths");
String recovered = st.getString("recovered");
if(statename.equals(value))
{
flag= 1;
}
statename = "State : " + statename;
active = "Active Cases : " + active;
confirmed = "Confirmed Cases : " + confirmed;
deaths = "Total Deaths : " + deaths;
recovered = "Total Recovered : " + recovered;
if(flag==1)
{
flag=0;
result.append(statename + "\n" + String.valueOf(active) + "\n" + String.valueOf(confirmed) + "\n" + String.valueOf(deaths) + "\n" + String.valueOf(recovered) + "\n\n\n");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mq.add(request);
}
}
Here , i want to pass the value of state entered by the user to the method jsonParse() so that i check the state name with the received JSON data and append it to the TextView, but when i do this , and try to log the value inside the jsonParse() method i get nothing, why is this happening , How do i implement the above ?

Your EditText value is update and has to be captured after the button is clicked.
parse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
value = text.getText().toString();
jsonParse(value);
}
});

Related

Cannot assign variables when doing JSON in android studio

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.

workaround for async call to read from Firebase

I'm new to Android and Firebase environment but I'm working on it !
I'm working on an Android app and I need to read some values related to a child within a Firebase database. After this initial read, I need to modify / update these values and write them to the same child.
public class MainActivity extends Activity {
public static class Shoe extends JSONObject {
private String name;
private int size;
Shoe(){
// Default constructor required for calls to
// DataSnapshot.getValue(Shoe.class)
}
Shoe( String nm, int sz) { this.name = nm; this.size = sz; }
public int getSize() { return this.size; }
public void setSize(int sz) { this.size = sz; }
public String getName() { return this.name;}
public void setName(String nm) {this.name = nm; }
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
// Write a message to the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
database.setPersistenceEnabled(true);
DatabaseReference myRefTarget = database.getReference("target");
Shoe obj1 = new Shoe("item ID 1", 99);
Shoe obj2 = new Shoe("item ID 2", 1000);
final Shoe obj_old = new Shoe();
Shoe obj_new = new Shoe();
DatabaseReference myRefDeviceA = myRefTarget.child("deviceA").getRef();
myRefDeviceA.keepSynced(true);
myRefDeviceA.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
obj_old.setName( dataSnapshot.getValue(Shoe.class).getName());
obj_old.setSize( dataSnapshot.getValue(Shoe.class).getSize());
Log.d(TAG_CLOUD, "from onDataChange: deviceA = " + obj_old.getName() + ", " + obj_old.getSize());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// HERE
Log.d(TAG_CLOUD, "Name = " + obj_old.getName() + ", Size = " + obj_old.getSize());
}
the issue I got is that the read operation is asynchronously done..
D/FROM CLOUD: Name = null, Size = 0
D/FROM CLOUD: from onDataChange: deviceA = item ID 1, 99
how can adapt / modify the source code in such way that first "read" to give me values different than null and '0' ? "HERE" line
eg.
Name = item ID 1 Size = 99
Thank you.
You don't suppose to perform networking operations on the UI thread.
If you want to display the data in the activity, you should show a loading dialog in the onCreate method, and then after fetching the data close the dialog and update the activity view

Recyclerview from SQLite displays empty page on first time

I am trying to populate recyclerview from an async task. and in Async task the data is fetched through API call and pushed to a SQLite table, then the list populates from the SQLite Table. The list fails to display on first load. But when I close the app and reopen the app, the list populates. Is this a general issue that need to be addressed properly or I am missing with something else?
public class KingsActivity extends AppCompatActivity {
RecyclerView mRecyclerView;
RecyclerView.Adapter mAdapter;
RecyclerView.LayoutManager mLayoutManager;
List<King> kingList=new ArrayList<King>();
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("method_track","onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//To avoid the load on the main thread
new DownloadDataAsync().execute(this);
}
public class DownloadDataAsync extends AsyncTask<Context, Integer, Context> {
#Override
protected Context doInBackground(Context... ctx) {
downloadData(ctx[0]);
return ctx[0];
}
#Override
protected void onProgressUpdate(Integer... progress) {
}
#Override
protected void onPostExecute(Context result) {
Log.d("method_track","PostExecute");
Cursor kingsRows=DatabaseHelper.getInstance(result.getApplicationContext()).getData(DatabaseHelper.TABLE_WESTEROS_KINGS);
kingsRows.moveToFirst();
while(kingsRows.moveToNext()){
String kingName=kingsRows.getString(kingsRows.getColumnIndex(DatabaseHelper.KEY_WESTEROS_KINGS_NAME));
int battleCount=kingsRows.getInt(kingsRows.getColumnIndex(DatabaseHelper.KEY_WESTEROS_KINGS_BATTLE_COUNT));
int rating=kingsRows.getInt(kingsRows.getColumnIndex(DatabaseHelper.KEY_WESTEROS_KINGS_RATING));
kingList.add(new King(kingName,rating,battleCount));
}
kingsRows.close();
mRecyclerView = (RecyclerView)findViewById(R.id.my_recycler_view);
mLayoutManager = new LinearLayoutManager(result);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new KingsAdapterRC(kingList,result);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
public void downloadData(final Context ctx){
// Get a RequestQueue
RequestQueue queue = HttpRequestHandler.getInstance(ctx.getApplicationContext()).
getRequestQueue();
String url ="http://starlord.hackerearth.com/gotjson";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
//Log.d("result_check",response.substring(0,500));
loadToDb(response,ctx);
populateList(ctx);
calculateRating(ctx);
logRatings(ctx);
//mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("result_check","Error");
//mTextView.setText("That didn't work!");
}
});
// Add a request to RequestQueue.
HttpRequestHandler.getInstance(ctx).addToRequestQueue(stringRequest);
}
protected void loadToDb(String jsonResponse,Context ctx){
DatabaseHelper.getInstance(ctx.getApplicationContext()).truncate(DatabaseHelper.TABLE_WESTEROS_DATA);
try {
JSONArray jsonArray = new JSONArray(jsonResponse);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObj = (JSONObject)jsonArray.get(i);
Iterator<String> iter = jsonObj.keys();
HashMap<String,String> fieldVales=new HashMap<String, String>();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = jsonObj.get(key);
fieldVales.put(key,value.toString());
} catch (JSONException e) {
// Something went wrong!
Log.e("loadTodb",e.toString());
}
}
DatabaseHelper.getInstance(ctx.getApplicationContext()).insert(DatabaseHelper.TABLE_WESTEROS_DATA,fieldVales);
}
} catch (Throwable t) {
//Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
}
protected void populateList(Context ctx){
List<King> kingList=new ArrayList<King>();
String[] kings;
int kingsCount=0;
String sql="SELECT DISTINCT "+DatabaseHelper.KEY_WESTEROS_ATTACKER_KING+ " FROM "+ DatabaseHelper.TABLE_WESTEROS_DATA
+" WHERE "+ DatabaseHelper.KEY_WESTEROS_ATTACKER_KING +" <> ''";
Cursor rows=DatabaseHelper.getInstance(ctx.getApplicationContext()).getReadableDatabase().rawQuery(sql, null);
kingsCount+=rows.getCount();
String sql2="SELECT DISTINCT "+DatabaseHelper.KEY_WESTEROS_DEFENDER_KING + " FROM "+ DatabaseHelper.TABLE_WESTEROS_DATA
+ " WHERE "+ DatabaseHelper.KEY_WESTEROS_DEFENDER_KING + " NOT IN ( "+sql+ " ) AND "
+ DatabaseHelper.KEY_WESTEROS_DEFENDER_KING +" <> ''";
Cursor rows2=DatabaseHelper.getInstance(ctx.getApplicationContext()).getReadableDatabase().rawQuery(sql2, null);
kingsCount+=rows2.getCount();
kings=new String[kingsCount];
int i=0;
if (rows.moveToFirst()) {
while (!rows.isAfterLast()) {
//your code to implement
kings[i]=rows.getString(rows.getColumnIndex(DatabaseHelper.KEY_WESTEROS_ATTACKER_KING));
i++;
rows.moveToNext();
}
}
rows.close();
if (rows2.moveToFirst()) {
while (!rows2.isAfterLast()) {
//your code to implement
kings[i]=rows2.getString(rows2.getColumnIndex(DatabaseHelper.KEY_WESTEROS_DEFENDER_KING));
i++;
rows2.moveToNext();
}
}
rows2.close();
DatabaseHelper.getInstance(ctx.getApplicationContext()).truncate(DatabaseHelper.TABLE_WESTEROS_KINGS);
for(i=0;i<kingsCount;i++){
HashMap<String,String> fieldValues=new HashMap<String, String>();
fieldValues.put(DatabaseHelper.KEY_WESTEROS_KINGS_NAME,kings[i]);
fieldValues.put(DatabaseHelper.KEY_WESTEROS_KINGS_RATING,"400");
fieldValues.put(DatabaseHelper.KEY_WESTEROS_KINGS_BATTLE_COUNT,"0");
DatabaseHelper.getInstance(ctx.getApplicationContext()).insert(DatabaseHelper.TABLE_WESTEROS_KINGS,fieldValues);
}
}
protected void calculateRating(Context ctx){
Cursor battles_cur=DatabaseHelper.getInstance(ctx.getApplicationContext()).getData(DatabaseHelper.TABLE_WESTEROS_DATA);
if(battles_cur.moveToFirst()){
while(!battles_cur.isAfterLast()){
String attackingKing=battles_cur.getString(battles_cur.getColumnIndex(DatabaseHelper.KEY_WESTEROS_ATTACKER_KING));
String defendingKing=battles_cur.getString(battles_cur.getColumnIndex(DatabaseHelper.KEY_WESTEROS_DEFENDER_KING));
if(!attackingKing.equals("") && !defendingKing.equals("")){
HashMap<String,String> whereConDfk=new HashMap<String,String>();
whereConDfk.put(DatabaseHelper.KEY_WESTEROS_KINGS_NAME,defendingKing);
Cursor cursor1=DatabaseHelper.getInstance(ctx.getApplicationContext()).getData(DatabaseHelper.TABLE_WESTEROS_KINGS,whereConDfk);
double defKing_rating;
double defKing_battleCount;
if(cursor1.moveToFirst()){
defKing_rating=cursor1.getDouble(cursor1.getColumnIndex(DatabaseHelper.KEY_WESTEROS_KINGS_RATING));
defKing_battleCount=cursor1.getDouble(cursor1.getColumnIndex(DatabaseHelper.KEY_WESTEROS_KINGS_BATTLE_COUNT));
cursor1.close();
HashMap<String,String> whereConAtk=new HashMap<String,String>();
whereConAtk.put(DatabaseHelper.KEY_WESTEROS_KINGS_NAME,attackingKing);
Cursor cursor2=DatabaseHelper.getInstance(ctx.getApplicationContext()).getData(DatabaseHelper.TABLE_WESTEROS_KINGS,whereConAtk);
Double atkKing_rating;
Double atkKing_battleCount;
if(cursor2.moveToFirst()){
atkKing_rating=cursor2.getDouble(cursor2.getColumnIndex(DatabaseHelper.KEY_WESTEROS_KINGS_RATING));
atkKing_battleCount=cursor2.getDouble(cursor2.getColumnIndex(DatabaseHelper.KEY_WESTEROS_KINGS_BATTLE_COUNT));
cursor2.close();
atkKing_battleCount++;
defKing_battleCount++;
Double defKing_rating_tr=Math.pow(10,(defKing_rating/400));
Double atkKing_rating_tr=Math.pow(10,(atkKing_rating/400));
Double defKing_rating_ex=defKing_rating_tr/(defKing_rating_tr+atkKing_rating_tr);
Double atkKing_rating_ex=atkKing_rating_tr/(defKing_rating_tr+atkKing_rating_tr);
String attackerStatus=battles_cur.getString(battles_cur.getColumnIndex(DatabaseHelper.KEY_WESTEROS_ATTACKER_OUTCOME));
Double atkKing_rating_new=atkKing_rating;
Double defKing_rating_new=defKing_rating;
if(attackerStatus.equals("win")){
atkKing_rating_new=atkKing_rating+(32*(1-atkKing_rating_ex));
defKing_rating_new=defKing_rating+(32*(0-defKing_rating_ex));
}else if(attackerStatus.equals("loss")){
atkKing_rating_new=atkKing_rating+(32*(0-atkKing_rating_ex));
defKing_rating_new=defKing_rating+(32*(1-defKing_rating_ex));
}else if(attackerStatus.equals("draw")){
atkKing_rating_new=atkKing_rating+(32*(0.5-atkKing_rating_ex));
defKing_rating_new=defKing_rating+(32*(0.5-defKing_rating_ex));
}
String update_atkKing_ratingQuery="UPDATE "+ DatabaseHelper.TABLE_WESTEROS_KINGS + " SET "
+ DatabaseHelper.KEY_WESTEROS_KINGS_RATING+" = "+atkKing_rating_new+", "
+ DatabaseHelper.KEY_WESTEROS_KINGS_BATTLE_COUNT+" = "+atkKing_battleCount
+ " WHERE "+ DatabaseHelper.KEY_WESTEROS_KINGS_NAME +" =\""+attackingKing+"\"";
String update_defKing_ratingQuery="UPDATE "+ DatabaseHelper.TABLE_WESTEROS_KINGS + " SET "
+ DatabaseHelper.KEY_WESTEROS_KINGS_RATING+" = "+defKing_rating_new+", "
+ DatabaseHelper.KEY_WESTEROS_KINGS_BATTLE_COUNT+" = "+defKing_battleCount
+ " WHERE "+ DatabaseHelper.KEY_WESTEROS_KINGS_NAME +" =\""+defendingKing+"\"";
DatabaseHelper.getInstance(ctx.getApplicationContext()).getWritableDatabase().execSQL(update_atkKing_ratingQuery);
DatabaseHelper.getInstance(ctx.getApplicationContext()).getWritableDatabase().execSQL(update_defKing_ratingQuery);
}
}
}
battles_cur.moveToNext();
}
}
}
protected void logRatings(Context ctx){
Log.d("method_track","logratings");
Cursor kings_cur=DatabaseHelper.getInstance(ctx.getApplicationContext()).getData(DatabaseHelper.TABLE_WESTEROS_KINGS);
try {
while (kings_cur.moveToNext()) {
String name=kings_cur.getString(kings_cur.getColumnIndex(DatabaseHelper.KEY_WESTEROS_KINGS_NAME));
String rating=kings_cur.getString(kings_cur.getColumnIndex(DatabaseHelper.KEY_WESTEROS_KINGS_RATING));
String battleCount=kings_cur.getString(kings_cur.getColumnIndex(DatabaseHelper.KEY_WESTEROS_KINGS_BATTLE_COUNT));
//Log.d("method_track", "logratings");
Log.d("rating_inspect",name+" - "+rating+" - "+battleCount);
}
}finally {
kings_cur.close();
}
}
}
}
Here:
downloadData(ctx[0]);
Problem caused by downloadData method.
In downloadData method using StringRequestto get data from server. StringRequest process all requests on worker Thread and return result back using Response.Listener.
doInBackground also done all work on worker Thread. so doInBackground method's Work Thread just executing downloadData method without waiting to get response from StringRequest.
No need to use extra Thread when using StringRequest. just remove AsyncTask and use only StringRequest to get it work properly.
Yo should not call volley StringRequest from doInBackground because async task immediately shot the post execute method and your list will be empty so that it won't show any data. Simply use string request and after getting response save it in your 'database' and fetch from there(you can save and fetch the data from database directly or using async task).
For not just use StringRequest without any async task and test it.

How to call GsonRequest multiple times/ in loop

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.

String is not recognised as used and is highlighted in grey despite everything being set public

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);
}

Categories

Resources