Get variable from onResponse - java

I want to get the variable "response" from the BDDRequest class for using it in a ListView in my MainActivity class, how i can do ?
public class BDDRequest implements Serializable {
private final long serialVersionUID = 1L;
static private Activity activity;
public String req;
public BDDRequest(){}
public static void GetRequest(final Context t, UserEmployeeInfo User) {
activity = (Activity) t;
RequestQueue queue = Volley.newRequestQueue(t);
ParamsSend params = new ParamsSend();
params.setUser(User);
ParserJson<ParamsSend> pj = new ParserJson<>(params);
String strJson;
try {
strJson = pj.writeJSON();
} catch (JsonProcessingException e) {
strJson = "null";
}
final String data = strJson;
String REST_API_URL = "http://212.227.53.116:8080/WSmartgroom/rest/perso/request";
Log.d("lol", strJson);
StringRequest myReq = new StringRequest(Request.Method.PUT,
REST_API_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("reponse:", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("That didn't work!", "Error");
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
return data.getBytes();
}
};
queue.add(myReq);
}
}

Use an interface for it,
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.io.Serializable;
public class BDDRequest implements Serializable {
private final long serialVersionUID = 1L;
static private Activity activity;
public String req;
public BDDRequest() {
}
public static void GetRequest(final Context t, UserEmployeeInfo User, final Callback callback) {
activity = (Activity) t;
RequestQueue queue = Volley.newRequestQueue(t);
ParamsSend params = new ParamsSend();
params.setUser(User);
ParserJson<ParamsSend> pj = new ParserJson<>(params);
String strJson;
try {
strJson = pj.writeJSON();
} catch (JsonProcessingException e) {
strJson = "null";
}
final String data = strJson;
String REST_API_URL = "http://212.227.53.116:8080/WSmartgroom/rest/perso/request";
Log.d("lol", strJson);
StringRequest myReq = new StringRequest(Request.Method.PUT,
REST_API_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("reponse:", response);
callback.onSuccess(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("That didn't work!", "Error");
callback.onError();
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
return data.getBytes();
}
};
queue.add(myReq);
}
public interface Callback {
void onSuccess(String response);
void onError();
}
}
And implement the interface on your class .
Use like this,
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import com.example.BDDRequest.Callback;
public class MainActivity extends FragmentActivity implements Callback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BDDRequest.GetRequest(this, new UserEmployeeInfo(), this);
}
#Override
public void onSuccess(String response) {
// Bind the data to the listview
}
#Override
public void onError() {
//Show fallback message here
}
}

You're declaring onResponse method. Inside it, response is a parameter. Why do you want to get a parameter which you're putting into? The question is not clear.

Related

Move method to another Java class, and call the method from the original class

Dear valued program gurus!
I need help on moving a method to another Java class.
I am having a Java class called ProfileList.java containing the following code:
package dk.timeleft.versionone;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class ProfileList extends AppCompatActivity {
Button btnGet;
Button btnPost;
TextView txtResult;
public String url;
public String postUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_list);
btnGet = (Button) findViewById(R.id.btnGet);
btnPost = (Button) findViewById(R.id.btnPost);
txtResult = (TextView) findViewById(R.id.txtResult);
btnGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
txtResult.setText("Retrieving GET-data");
url = "https://kairosplanner.com/api/timeleft.php";
try {
getResponse();
} catch (IOException e) {
e.printStackTrace();
}
}
});
btnPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
txtResult.setText("Retrieving POST-data");
postUrl = "https://kairosplanner.com/api/timeleft2.php/";
RequestBody postBody = new FormBody.Builder()
.add("first_name", "Hans")
.add("last_name", "Schmidt")
.build();
try {
postRequest(postUrl, postBody);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
void postRequest(String postUrl, RequestBody postBody) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(postUrl)
.post(postBody)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
final String myResponse = response.body().string();
ProfileList.this.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject json = new JSONObject(myResponse);
//txtString.setText("First Name: "+json.getJSONObject("data").getString("first_name") + "\nLast Name: " + json.getJSONObject("data").getString("last_name"));
txtResult.setText(json.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
void getResponse() throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
final String myResponse = response.body().string();
ProfileList.this.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject json = new JSONObject(myResponse);
//txtString.setText("First Name: "+json.getJSONObject("data").getString("first_name") + "\nLast Name: " + json.getJSONObject("data").getString("last_name"));
txtResult.setText(json.toString());
Toast.makeText(ProfileList.this,"Hello",Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
public class OkHttpHandler extends AsyncTask<String, Void, String> {
OkHttpClient client = new OkHttpClient();
#Override
protected String doInBackground(String... params) {
Request.Builder builder = new Request.Builder();
builder.url(params[0]);
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
return response.body().string();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//txtString.setText(s);
}
}
}
This is working without any problems, but I'd like to have my code clean an neat.
I will be using the POST and GET functions (postRequest and getResponse methods) often, also in other Java classes, so it would be better, I guess, if those methods, including the OkHttpHandler class, to a separate Java class, e.g. ApiCommunicator.java, and call the methods from there.
I found a lot of information on how to refactor, but that just deletes the current ProfileList.java class.
I also tried just to copy the methods (postRequest, getResponse and OkHttpHandler to ApiCommunicator.java (and afterwards delete these methods from ProfileList.java), but that gives a few other problems, e.g. the .runOnUiThread runnable within the OnResponse method in postRequest and getResponse - those refer to ProfileList.this in stead of a dynamic Java class.
So my question is: how do I move a method from one class to another, and call the method from the original class?
BTW: I am using IntelliJ
I hope somebody can help me with this problem.
EDITED: Added ApiCommunicatorListener interface to ApiCommunicator that needs to be implemented by ProfileList activity to get the result back and assign it to txtResult.
You could create your ApiCommunicator class like so:
public class ApiCommunicator<T extends AppCompatActivity & ApiCommunicator.ApiCommunicatorListener> {
private T activity;
public ApiCommunicator(T activity) {
this.activity = activity;
}
public void postRequest(String postUrl, RequestBody postBody) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(postUrl)
.post(postBody)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
final String myResponse = response.body().string();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject json = new JSONObject(myResponse);
activity.postRequestResult(json.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
public void getResponse() throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
final String myResponse = response.body().string();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject json = new JSONObject(myResponse);
activity.getResponseResult(json.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
public interface ApiCommunicatorListener {
void postRequestResult(String result);
void getResponseResult(String result);
}
}
After that, you need to implement the interface in ProfileList activity like so:
public class ProfileList extends AppCompatActivity implements ApiCommunicator.ApiCommunicatorListener {
Then you're gonna add those two methods to ProfileList:
#Override
public void postRequestResult(String result) {
txtResult.setText(result);
}
#Override
public void getResponseResult(String result) {
txtResult.setText(result);
}
And finally use ApiCommunicator:
ApiCommunicator apiCommunicator = new ApiCommunicator<>(this);
apiCommunicator.postRequest(...);
apiCommunicator.getRequest(...);

return data from method (JSON Array)

I have one method with this url:
String url = "http://brunos.000webhostapp.com/teste/obter_id.php?descricao=" + value;
And i want to return the result of this method.
i have tried the VolleyCallback callback but i cant send the value to the method
package com.example.fabio.domoticaa;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Divi_Dispo extends AppCompatActivity {
String x;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_divi__dispo);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final String[] count = new String[1];
final String[] id = new String[1];
Intent intent = getIntent();
String value = intent.getStringExtra("divisao");
final EditText nomediv = (EditText) findViewById(R.id.editText4);
Count(value);
nomediv.setText(x);//want set th result of Count(value)
}
public void Count(String value) {
final String[] count = new String[1];
// Send data
try {
RequestQueue queue = Volley.newRequestQueue(Divi_Dispo.this);
String url = "http://brunos.000webhostapp.com/teste/obter_id.php?descricao=" + value ;
JsonArrayRequest jsonRequest = new JsonArrayRequest
(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONObject jObj = new JSONObject(String.valueOf(response.get(0)));
count[0] = jObj.getString("COUNT(id)");//want return this valor
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonRequest);
} catch (Exception ex) {
} finally {
}
}
public interface VolleyCallback {
void onSuccess(String result);
}
}

How to post boolean value using volley

I am trying to post boolean value using volley library.When a button is clicked,a boolean value is set to true.The boolean value is then posted to my php script to increment counter in my mysql database. i am getting an error in trying to add a request to queue. What am i doing wrong? This is my code
holder.custom_button.setOnClickListener(new View.OnClickListener() {
int count;
#Override
public void onClick(View v) {
count = 0;
superHeroes.get(position).setCount(superHeroes.get(position).getCount() + 1);
holder.txtCount.setText(superHeroes.get(position).getCount() + "");
final String url = "http://10.0.2.2/likes.php";
isLiked = true;
JSONObject obj = new JSONObject();
try {
obj.put("isLiked", true);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
// Access the RequestQueue through your singleton class.
// i am getting error here
customVolleyRequest.getInstance(this).addToRequestQueue(jsObjRequest);
}
});
SINGLETON
package net.simplifiedcoding.myfeed;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.ImageLoader;
/**
* Created by Belal on 12/5/2015.
*/
public class CustomVolleyRequest {
private static CustomVolleyRequest customVolleyRequest;
private static Context context;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private CustomVolleyRequest(Context context) {
this.context = context;
this.requestQueue = getRequestQueue();
imageLoader = new ImageLoader(requestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized CustomVolleyRequest getInstance(Context context) {
if (customVolleyRequest == null) {
customVolleyRequest = new CustomVolleyRequest(context);
}
return customVolleyRequest;
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024);
Network network = new BasicNetwork(new HurlStack());
requestQueue = new RequestQueue(cache, network);
requestQueue.start();
}
return requestQueue;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
ERROR
'getInstance(android.content.Context)' in 'net.simplifiedcoding.myfeed.CustomVolleyRequest' cannot be applied to '(anonymous android.view.View.OnClickListener)'
You are not making POST request. You should do like this:
JsonObjectRequest req = new JsonObjectRequest( Request.Method.POST, url,
new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Handle response
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle Error
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
AppController.getInstance().addToRequestQueue(req); // AppController is Volley Singleton.
You have used CardAdapter, I don't what that is. You should always add the request object to Volley Singleton. Reference.

java.lang.NullPointerException: Attempt to invoke virtual methodon a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
So I'm working on a personal app that displays JSON data using CardView and RecycleView, however I'm constantly getting this NullPointerException and I have no idea how I should approach to debug this and I could really use some help.
These are the errors I'm getting
{java.lang.RuntimeException: Unable to start activity ComponentInfo{com.brokenbroadcast.nba_project/com.brokenbroadcast.nba_project.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.brokenbroadcast.nba_project.NBA.getGameList()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3149)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3257)
at android.app.ActivityThread.access$1000(ActivityThread.java:197)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1681)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6891)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:115)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.brokenbroadcast.nba_project.NBA.getGameList()' on a null object reference
at com.brokenbroadcast.nba_project.MainActivity.onCreate(MainActivity.java:52)
at android.app.Activity.performCreate(Activity.java:6550)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1120)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3102)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3257) 
at android.app.ActivityThread.access$1000(ActivityThread.java:197) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1681) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:6891) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
From my understanding it is having problem with my code at MainActivity.java:52.
Here is my MainActivity.java
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private List<Game> gameList;
private NBA mNBA;
public static final String TAG = MainActivity.class.getSimpleName();
public static final String mScoreboardUrl = "http://data.nba.com/5s/json/cms/noseason/scoreboard/20160116/games.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
RecyclerView recList = (RecyclerView) findViewById(R.id.cardList);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
gameList = new ArrayList<Game>();
setUpGames();
GameAdapter ca = new GameAdapter(mNBA.getGameList());
recList.setAdapter(ca);
}
private void setUpGames() {
if (isNetworkAvailable()) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(mScoreboardUrl).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
if (response.isSuccessful()) {
mNBA = parseNBADetails(jsonData);
} else {
alertUserAboutError();
}
} catch (IOException e) {
} catch (JSONException j) {
}
}
});
} else {
Toast.makeText(this, getString(R.string.network_unavailable_message),
Toast.LENGTH_LONG).show();
}
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private NBA parseNBADetails(String jsonData) throws JSONException {
NBA nba = new NBA();
nba.setGameList(parseGames(jsonData));
return nba;
}
private List<Game> parseGames(String jsonData) throws JSONException {
JSONObject sports_content = new JSONObject(jsonData);
JSONObject schedule = sports_content.getJSONObject("sports_content");
JSONObject gameArray = schedule.getJSONObject("games");
JSONArray data = gameArray.getJSONArray("game");
List<Game> gameList = new ArrayList<Game>();
for (int i = 0; i < data.length(); i++) {
Game game = new Game();
JSONObject jsonGame = data.getJSONObject(i);
JSONObject jsonVisitor = jsonGame.getJSONObject("visitor");
game.setVisitorTeamName(jsonVisitor.getString("nickname"));
game.setVisitorScore(jsonVisitor.getInt("score"));
game.setVisitorTeamLocation(jsonVisitor.getString("city"));
JSONObject jsonHome = jsonGame.getJSONObject("home");
game.setHomeTeamLocation(jsonHome.getString("city"));
game.setHomeTeamName(jsonHome.getString("nickname"));
game.setHomeScore(jsonHome.getInt("score"));
Log.i(TAG, game.getHomeScore() + "");
gameList.add(game);
}
return gameList;
}
}
This is my class NBA.java
public class NBA {
private List<Game> mGameList;
public List<Game> getGameList() {
return mGameList;
}
public void setGameList(List<Game> gameList) {
mGameList = gameList;
}
}
This is my Game.java
public class Game {
private int mHomeScore;
private int mVisitorScore;
private String mHomeTeamLocation;
private String mHomeTeamName;
private String mVisitorTeamLocation;
private String mVisitorTeamName;
public String getHomeTeamLocation() {
return mHomeTeamLocation;
}
public Game(){}
public void setHomeTeamLocation(String homeTeamLocation) {
mHomeTeamLocation = homeTeamLocation;
}
public String getHomeTeamName() {
return mHomeTeamName;
}
public void setHomeTeamName(String homeTeamName) {
this.mHomeTeamName = homeTeamName;
}
public String getVisitorTeamLocation() {
return mVisitorTeamLocation;
}
public void setVisitorTeamLocation(String visitorTeamLocation) {
mVisitorTeamLocation = visitorTeamLocation;
}
public String getVisitorTeamName() {
return mVisitorTeamName;
}
public void setVisitorTeamName(String visitorTeamName) {
mVisitorTeamName = visitorTeamName;
}
public String getTitle() {
return getHomeTeam() + " vs. " + getVisitorTeam();
}
public String getHomeTeam() {
return mHomeTeamLocation+" " +mHomeTeamName;
}
public String getVisitorTeam() {
return mVisitorTeamLocation+" "+mVisitorTeamName;
}
public int getHomeScore() {
return mHomeScore;
}
public void setHomeScore(int homeScore) {
mHomeScore = homeScore;
}
public int getVisitorScore() {
return mVisitorScore;
}
public void setVisitorScore(int visitorScore) {
mVisitorScore = visitorScore;
}
}
My GameAdapter.java
package com.brokenbroadcast.nba_project;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by steven on 1/16/2016.
*/
public class GameAdapter extends RecyclerView.Adapter<GameAdapter.GameViewHolder> {
private List<Game> mGameList = new ArrayList<Game>();
public GameAdapter(List<Game> gameList){
mGameList=gameList;
}
#Override
public GameViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view, parent, false);
return new GameViewHolder(itemView);
}
#Override
public void onBindViewHolder(GameViewHolder holder, int position) {
Game curGame = mGameList.get(position);
holder.vHomeScore.setText(curGame.getHomeScore()+"");
holder.vVisitorScore.setText(curGame.getVisitorScore()+"");
holder.vTitle.setText(curGame.getTitle());
holder.vVisitorTeam.setText(curGame.getVisitorTeam());
}
#Override
public int getItemCount() {
return mGameList.size();
}
public class GameViewHolder extends RecyclerView.ViewHolder {
private TextView vHomeTeam;
private TextView vVisitorTeam;
private TextView vTitle;
private TextView vHomeScore;
private TextView vVisitorScore;
public GameViewHolder(View v) {
super(v);
vHomeTeam = (TextView) v.findViewById(R.id.homeTeam);
vVisitorTeam = (TextView) v.findViewById(R.id.visitorTeam);
vHomeScore = (TextView) v.findViewById(R.id.homeScore);
vVisitorScore = (TextView) v.findViewById(R.id.visitorScore);
vTitle = (TextView) v.findViewById(R.id.gameTitle);
}
}
}
If anyone could help me I will really appreciate it.
It looks like the assignment mNBA = parseNBADetails(jsonData); doesn't take place on the same thread as GameAdapter ca = new GameAdapter(mNBA.getGameList());, so mNBA may still be null when the latter statement is called.
A possible solution is to put that statement in the same thread that initializes mNBA :
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
if (response.isSuccessful()) {
mNBA = parseNBADetails(jsonData);
GameAdapter ca = new GameAdapter(mNBA.getGameList()); // moved from onCreate
recList.setAdapter(ca); // moved from onCreate
} else {
alertUserAboutError();
}
} catch (IOException e) {
} catch (JSONException j) {
}
}
In the following line you are trying to access a list which has never been initialized.
GameAdapter ca = new GameAdapter(mNBA.getGameList());
Make sure mNBA is not null. You only declare the variable but never assigned any value to it.
Also declare :
private NBA mNBA = new NBA();

Async class not passing the argument

My async class is throwing some errors. The line with AsyncLoadData says that I should create local variable url
public void getData() {
new AsyncLoadData(this,this).execute(url);
}
My AsyncLoadData class
package com.example.hay;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.EditText;
public class AsyncLoadData extends AsyncTask<String, Void, String> {
private Context mContext;
private ILoadDataListener mListener;
public AsyncLoadData(Context context, ILoadDataListener listener) {
this.mContext = context;
this.mListener = listener;
}
#Override
protected String doInBackground(String... params) {
try {
EditText tf = (EditText) this.findViewById(R.id.editText1);
String url = params[0];
url = tf.getText().toString();
Document doc;
doc = Jsoup.connect(url).get();
String title = doc.text();
return title;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private EditText findViewById(int edittext1) {
return null;
}
#Override
protected void onPostExecute(String result) {
mListener.complete(result);
}
#Override
protected void onPreExecute() {
mListener.loading();
}
public interface ILoadDataListener {
void loading();
void complete(String result);
}
}
As you can see the AsyncLoadData should pass the url variable.
Have you declared url somewhere else in the code before calling this line : new AsyncLoadData(this,this).execute(url); ?
If not, you should add line String url = "the value of the url you are trying to call"; just before it, otherwise the variable url does not exist in the getData method...

Categories