我创建了一个应返回二维数组的方法,一切都运行良好,因为数组在方法的try
中正确填充。 但是一旦我在onCreate()
上显示数组,它就会返回 null。
public class ListTickets extends AppCompatActivity {
public String[][] ticketTab ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_tickets);
ticketTab = new String[Integer.valueOf(nbTicket)][nbTicketTab];
DisplayArray(getTicketsHTTP());
}
private String[][] getTicketsHTTP() {
final JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, URL, null,
new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response) {
try {
JSONArray Jdata = response.getJSONArray("data");
for (int i=0; i < Jdata.length(); i++) {
try {
JSONObject oneTicket = Jdata.getJSONObject(i);
titreTicket = oneTicket.getString("1");
slaTicket = oneTicket.getString("30");
dateDebutTicket = oneTicket.getString("15");
urgenceTicket = oneTicket.getString("10");
statutTicket = oneTicket.getString("12");
idTicket = oneTicket.getString("2");
} catch (JSONException e) {
Log.e("Err", e.getMessage());
}
ticketTab[i][0] = titreTicket;
ticketTab[i][1] = slaTicket;
ticketTab[i][2] = dateDebutTicket;
ticketTab[i][3] = urgenceText(urgenceTicket);
ticketTab[i][4] = calculTempsRestant(dateDebutTicket, slaTicket, dateEchanceTicket);
ticketTab[i][5] = String.valueOf(ticketEnretard);
ticketTab[i][6] = statutTicket;
ticketTab[i][7] = idTicket;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Error.Response", error.toString());
}
}
){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("App-Token",FirstEverActivity.App_Token);
params.put("Session-Token",session_token);
return params;
}
};
// add it to the RequestQueue
queue.add(getRequest);
return ticketTab;
}
}
我在onCreate
外部声明了 ticketTab,因为当我在方法中声明它时,我无法在try
内更改它。 如何正确返回数组?
在 onCreate 中,您正在使用以下行:
ticketTab = new String[Integer.valueOf(nbTicket)][nbTicketTab];
这些值、nbTicket
和nbTicketTab
没有在您的代码中的任何位置声明,也许这就是它们返回 null 的原因,您必须初始化它们并分配值。