Running Async in a fragment is not even being ran - android

I am running the commands like so:
new GetGameScoresFromFuhantikAPI()
And my method for this is ->
private class GetGameScoresFromFuhantikAPI extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
MethodContants.showLog(TAG, "Loading FUHNATIK API", true);
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = API_URL + jsonFile;
// String url = "http://www.nfl.com/liveupdate/game-center/" + list.get(i) + "/" + list.get(i) + "_gtd.json";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from FUHNATIK API: " + url);
if (jsonStr != null) {
try {
//JSONObject object = new JSONObject(json);
JSONObject object = new JSONObject(jsonStr);
currentWeek = object.getString("pypwk");
currentWeekDB = object.getString("mdb");
JSONArray array = (JSONArray) object.get("g");
scheduleModelList = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
//TODO IF WE DONT PLAY THURSDAY GAMES PUT LIST.ADD IN HERE
// if (!array.getJSONObject(i).getString("-d").equals("Thu")){
//
// }
scheduleModelList.add(new ScheduleModel(array.getJSONObject(i).getString("-v"),
array.getJSONObject(i).getString("-h"),
array.getJSONObject(i).getString("-t"),
array.getJSONObject(i).getString("-d"),
array.getJSONObject(i).getString("-eid").substring(0, 8),
array.getJSONObject(i).getString("-t") + array.getJSONObject(i).getString("-q"),
array.getJSONObject(i).getString("-vnn"),
array.getJSONObject(i).getString("-hnn"),
"...select a team...",
array.getJSONObject(i).getString("-eid"),
array.getJSONObject(i).getString("-vs"),
array.getJSONObject(i).getString("-hs"),
array.getJSONObject(i).getString("-w")));
}
} catch (final JSONException e) {
Log.e(TAG, "FUHNATIK API: Json parsing error: " + e.getMessage());
}
} else {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e(TAG, "FUHNATIK API: Couldn't get json from server.");
Toast.makeText(getContext(), "Getting from ESPN", Toast.LENGTH_SHORT).show();
//new GetGameScoresFromESPN().execute();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
final ListViewAdapterResults adapter = new ListViewAdapterResults(listView.getContext(), scheduleModelList);
listView.setAdapter(adapter);
MethodContants.showLog(TAG, "DONE WITH LOADING FUHNATIK API", false);
}
}
I can't seem to figure out why the code never get ran. I ran through the debugger but I really can't pinpoint where this is failing out. Any help on this would be appreciated.
Eventually if the json file is not at this URL, I will be getting the json from NFL. However, Without this working, the ESPN won't work either, and I really can not figure out where the error is on my end. I have to assume this will be a pretty easy fix.
Again, as said before, any help would be very appreciated!!

In the above line of code you call the Class but you forgot to execute your asynctask. So no Overriden methods are called. Try this:
new GetGameScoresFromFuhantikAPI().execute();
If you want to pass something as argument, give parameters separated by coma like this:
new GetGameScoresFromFuhantikAPI().execute(arg0, arg1);

Related

Null reference in listadpter when looping through JSON [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am getting some json from a simple api, to show in a listview.
public class ScenariosActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView ScenarioListView ;
ArrayList<HashMap<String, String>> scenarioList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scenarios);
ScenarioListView = findViewById(R.id.scenariosListView);
new getScenarios().execute();
}
#SuppressLint("StaticFieldLeak")
class getScenarios extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(ScenariosActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... voids) {
HttpHandler httpHandler = new HttpHandler();
String url = "https://40kapi.evinwijninga.com/scenarios";
String jsonStr = httpHandler.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray scenarios = jsonObject.getJSONArray("scenarios");
Log.e(TAG, "JSONARRAY :"+scenarios);
for (int i = 0; i < scenarios.length(); i++){
Log.e(TAG, "Scenario's length: "+String.valueOf(scenarios.length()));
JSONObject s = scenarios.getJSONObject(i);
String id = null;
String title = null;
if (s.getString("id") != null) {
id = s.getString("id");
Log.e(TAG, id);
} else {
Log.e(TAG, "id = null");
}
if (s.getString("title") != null) {
title = s.getString("title");
Log.e(TAG, title);
} else {
Log.e(TAG, "title = null");
}
if (id != null && title != null){
// make new scenario
HashMap<String, String> scenario = new HashMap<>();
// add properties to scenario
scenario.put("id", id);
scenario.put("title", title);
// add scenario to scenariolist
scenarioList.add(scenario);
} else {
Log.e(TAG, "id or title is null");
}
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
ListAdapter adapter = new SimpleAdapter(ScenariosActivity.this, scenarioList,
R.layout.scenario_list_item, new String[]{"title"},
new int[]{R.id.title});
ScenarioListView.setAdapter(adapter);
}
}
}
When executed I get a null reference:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
I logged the length of the array, and it is 3, which is fine. I get the id and string of the first jsonobject logged, and that's it.
When looping through the json array for its objects I do something wrong.
Inititalize your ArrayList scenarioList as :
ArrayList<HashMap<String, String>> scenarioList = new ArrayList<>();
Here you are trying to access scenarioList without initialization by which it is null and you are getting null pointer exception.

Simplest straight forward way to get a JSON String from a REST URL

I am trying to get a JSON string from a url and save it into SQLite in my android app.
I was trying some tutorials then realize the suggested methods has a void return type. Are there a more simple straight forward way of getting a JSON String and putting it into an arraylist ready to be saved into SQLite?
Below is what I was stuck at a helper class that gets the data from the url
as they said that the main thread OnCreate does not allow a background process like this. Is there a way to change the return type of AsyncTask or is there a more simple way to fetch JSON String with android?
public class FetchData extends AsyncTask<Void, Void, Void> {
#Override
protected void doInBackground(ArrayList<String>... voids) {
try {
URL url = new URL("http://192.168.403.211/api/wordsupdate.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader (new InputStreamReader(inputStream));
String line ="";
while (line != null) {
line = bufferedReader.readLine();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Go with Volley API. Check the code below which demonstrate POST request. Hope you'll get useful information.
public void getAddress(final String uid) {
String url = "Add Url Here"; // Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray dataArray;
JSONObject jsonObject;
address_ids = new ArrayList<>();
address_names = new ArrayList<>();
address_line1 = new ArrayList<>();
address_line2 = new ArrayList<>();
address_state = new ArrayList<>();
address_district = new ArrayList<>();
address_taluka = new ArrayList<>();
address_pincode = new ArrayList<>();
address_status = new ArrayList<>();
address_default = new ArrayList<>();
try {
jsonObject = new JSONObject(response);
dataArray = jsonObject.getJSONArray(JSON_ARRAY);
//adding response values to respective array
for (int i = 0; i < dataArray.length(); i++) {
//Creating a json object of the current index
JSONObject obj;
try {
//getting json object from current index
obj = dataArray.getJSONObject(i);
address_ids.add(obj.getString(TAG_ADDRESS_ID));
address_names.add(obj.getString(TAG_ADDRESS_NAME));
address_line1.add(obj.getString(TAG_ADDRESSLINE_FIRST));
address_line2.add(obj.getString(TAG_ADDRESSLINE_SECOND));
address_state.add(obj.getString(TAG_STATE));
address_district.add(obj.getString(TAG_DISTRICT));
address_taluka.add(obj.getString(TAG_TALUKA));
address_pincode.add(obj.getString(TAG_PINCODE));
address_status.add(obj.getString(TAG_ADDRESS_STATUS));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//setting up response values to the fragment
//Toast.makeText(getActivity(), "Error:"+response, Toast.LENGTH_LONG).show();
Log.e(TAG, "onResponse: " + response);
address_name.setText("Name : " + address_names.get(0));
address.setText("Address : " + address_line1.get(0) + "," + address_line2.get(0) + "-" + address_pincode.get(0));
taluka.setText("Taluka : " + address_taluka.get(0));
district.setText("District : " + address_district.get(0));
state.setText("State : " + address_state.get(0));
mCircularProgressBar.setIndeterminate(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplication(), "Taking bit longer", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("mk_address_id", address_id);
return params;
}
};
queue.add(stringRequest);
}
Check this link from Android developer, you can find more info their.
In your code change the "extends" from
AsyncTask<Void, Void, Void>
to
AsyncTask<Void, Void, String>
and the doInBackground method to
protected String doInBackground(ArrayList<String>... voids)
and you will get the string back in the onPostExecute method
Yes there is a way to change the return types: Have a look at your extends AsyncTask: It says AsyncTask<Void, Void, Void>.
According to Android Developers, this means <Params, Progress, Result>.
This means that your
ArrayList<String>... voids won't work too, because you have the Params part set to Void but try to get an ArrayList<String>.
So, to solve your problem, change the three Voids to whatever you need it to input and output.
However, to deserialize JSON you should use an external library (or use a 3rd party library for REST calls altogether).
//AsyncTask has onPostExecute which will be called after background execution, where you will get the result in mainthread
class FetchData extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL("http://192.168.403.211/api/wordsupdate.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
//Your result String is here which runs on MAIN THREAD
super.onPostExecute(result);
}
}
Retrofit 2 will help you - easy and simple
Edit : For Async task see the top answer here
What arguments are passed into AsyncTask<arg1, arg2, arg3>?
In your code snippet , you specified AsyncTask params types are Void. Void means , it does't have any return value. As per AsyncTask Syntax,
You have to specify three arguments.
1- InputType- DoInBanckground
2- ProgressType - Publish Progress.
3- OutputType - OnPostExecute.
The three types used by an asynchronous task are the following:
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.
In your snippet doInBackground method and AsycTask types are mismatching .
For more information : https://developer.android.com/reference/android/os/AsyncTask.html

Getting data from Server too slow ? (Android)

I am trying to populate RecyclerView by the list of transactions i get from the server . but unless i put a Thread.sleep(7000) , it won't populate .
Does it take this much time to get data from server side ? If yes , Is there any faster alternative ?
or is getting the string from json response and adding object to list is time consuming ? because this sleep is just working for adding 5 rows in list. when i try to run loop for whole number of rows i don't get any data .
My host is PythonAnywhere .
API response is in json and has around 400 records :
http://sairav.pythonanywhere.com/getTransaction
Using :
Android Asynchronous Http Client:::
compile 'com.loopj.android:android-async-http:1.4.9'
public List<Transaction> getTransactions(final boolean getAll) {
Thread bgThread =null;
final List<Transaction> trList=new ArrayList<>();
RequestParams requestParams = new RequestParams();
requestParams.put("uid", Profile.getCurrentProfile().getId());
PAAPI.post("/getTransaction", requestParams, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray jsonArray) {
Transaction trr = null;
if (getAll) {
for (int i = 0; i < 5; i++) {
try {
//String a = jsonArray.getString(i);
JSONObject jsonObject = jsonArray.getJSONObject(i);
//JSONArray arrayWithElements = jsonObject.toJSONArray(new JSONArray(new String[]{"name","desc","amount","ttype","uid","ttime"}));
trr = new Transaction(context);
trr.uname = jsonObject.getString("uname");
trr.desc = jsonObject.getString("description");
trr.amount = jsonObject.getString("amount");
trr.type = jsonObject.getString("type");
trr.uid = jsonObject.getString("uid");
trr.date = jsonObject.getString("ttime");
trList.add(trr);
// Toast.makeText(context,"size is bro :"+trList.size(),Toast.LENGTH_SHORT).show();
if (i == 1) {
// Toast.makeText(context, trr.uname + "-" + desc + "-" + trr.amount + "-" + trr.type + "-" + trr.uid + "-" + trr.date, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// Do something with the response
}
});
try {
Toast.makeText(context,"sleeping bo",Toast.LENGTH_SHORT).show();
Thread.sleep(7000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Toast.makeText(context, "listsize final is" + trList.size(), Toast.LENGTH_SHORT).show();
return trList;
}
class PAAPI {
protected static final String BASE_URL = "http://sairav.pythonanywhere.com";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
If you are certain that getString() operation is taking too much time to perform then you can use progress dialog instead of using Thread.sleep()
private class PAAPI extends AsyncTask<Boolean, Void, List<Transaction> {
ProgressDialog dialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
//set message of the dialog
dialog.setMessage("Loading...");
//show dialog
dialog.show();
super.onPreExecute();
}
protected Void doInBackground(Boolean... args) {
// do background work here
return null;
}
protected void onPostExecute(List<Transaction> result) {
// do UI work here
if(dialog != null && dialog.isShowing()){
dialog.dismiss()
}
}
}
and later use it as new PAAPI().execute(getAll);
Use the retrofit library available to retrieve or post the data from a JSON URL ...it is very easy to use and is efficient

can not resolve method get(int)

After getting response from server i am storing points in my integer array and i am trying to add that array in my horizontal scrollview,but it gives me error in my loop,following is my code can anyone help?thanks advance
Error near this line
tv.setText(points.get(i));
JAVA
protected ArrayList<HashMap<String, String>> doInBackground(
String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(PLACE_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
placejsonObj = new JSONArray(jsonStr);
// state_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
jobject = placejsonObj.getJSONObject(0);
msgs=jobject.getString("user_status");
pointsarray=placejsonObj.getJSONArray(1);
// points=pointsarray.getString("point");
System.out.println("Kya yar" + "Failure"+pointsarray);
points = new int[pointsarray.length()];
for(int m=0; m<pointsarray.length(); m++) {
points[m] = pointsarray.getJSONObject(m).getInt("point");
}
System.out.println("array contains" + points.length + " elements");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
pDialog.dismiss();
for (int i = 0; i < points.length; i++) {
tv = new TextView(getActivity());
tv.setText(points[i]+",");
tv.setTag(points[i]);
yourLayout.addView(tv);
}
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int point = (int) view.getTag();
Toast.makeText(getActivity(),point,Toast.LENGTH_SHORT).show();
}
});
}
}
points is an array so do like
tv.setText(""+points[i]);
To get item from Array Use points[i] and to get item from List use points.get(i);
You have 2 problems as I see. The first is you try to set the text using an int, and the second is the way you try to access the data in the array (you use it like a list). Try it like this:
tv.setText(points[i] + "");

ProgressDialog cannot stop when load JSON

please help, I've given up on finding a solution
Data json already be in ArrayList, nothing error found but the progressdialog can't stop loading. I'm already put PG.dismis in postExecute but even the Adapter cannot changed.
private static List<DataVoucher> processResponse(String response) {
List<DataVoucher> list = new ArrayList<DataVoucher>();
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray jsonArray = jsonObj.getJSONArray("produk");
Log.d(TAG, "data lengt: " + jsonArray.length());
DataVoucher dataVoucher = null;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
dataVoucher = new DataVoucher();
dataVoucher.setKode(obj.getString("kode"));
dataVoucher.setHrg(obj.getString("hrg"));
dataVoucher.setNom(obj.getString("nom"));
dataVoucher.setKet(obj.getString("ket"));
list.add(dataVoucher);
listvoucher.add(obj.getString("nom"));
}
} catch (JSONException e) {
Log.d(TAG, e.getMessage());
}
return list;
}
public static String requestDataVoucher(final String operator) {
final String TAG = "SEND JSON";
Thread thread = new Thread() {
public void run() {
Looper.prepare();
JSONObject jsonObjSend = new JSONObject();
try {
jsonObjSend.put("type", "svoc");
jsonObjSend.put("hp", "089631633614");
jsonObjSend.put("opr", operator);
Log.i(TAG, jsonObjSend.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
SendHttpPost(jsonObjSend);
Looper.loop();
}
};
thread.start();
return TAG;
}
private class MainActivityAsync extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("retrieving...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String response = requestDataVoucher(pilihOperator
.getSelectedItem().toString());
list = processResponse(response);
return null;
}
#Override
protected void onPostExecute(String result) {
adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_item, listvoucher);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
pilihVoucher.setAdapter(adapter);
adapter.notifyDataSetChanged();
if (!adapter.isEmpty()) {
progressDialog.dismiss();
} // this is annoying
}
}
adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_spinner_item, listvoucher);
I think u mean
adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_spinner_item, list);
Btw just dismiss ur progressDialog at onPostExecute() not checking anything and maybe warn the user if the list is empty so you will evade these problems.
Many issues here
doInBackground is running in a thread, different from the ui thread. You are calling requestDataVoucher which is also creating a new thread, useless in this case.
You are calling processResponse with the String response which is the result of requestDataVoucher. According to your code, response equals "SEND JSON". So JSONObject jsonObj = new JSONObject(response); will trigger an Exception, listvoucher will remain empty, and so will your adapter. Conclusion, adapter is empty, the progressDialog won't disappear.
I can't propose a fix, as SendHttpPost is unknown. But as far as goes my understanding, you should remove the Thread creation from requestDataVoucher and return the JSON String generate by SendHttpPost.

Categories

Resources