我正在尝试将一个数组的字符串设置为TextView。我正在尝试这样的事情:
public class promo extends Fragment {
private int date;
private String[] gp_market = new String[5];
Calendar calendar = Calendar.getInstance();
TextView super_1;
public promo() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_news,
container, false);
super_1 = (TextView) view.findViewById(R.id.super_1);
final RequestQueue gpQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
date = calendar.get(Calendar.MONTH);
final String url = "myurl_webservice.php?date="+date; //edited
final JsonArrayRequest gp_request = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response)
try
for(int i=0; i < response.length(); i++){
JSONObject gp_object = response.getJSONObject(i);
gp_market[i] = gp_object.getString("product");
}
//I can see the data, the parsing is working.
Toast.makeText(getActivity().getApplicationContext(), gp_market[0], Toast.LENGTH_LONG).show();
}catch (JSONException e){
Toast.makeText(getActivity().getApplicationContext(), "Error " + e.toString(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.toString() , Toast.LENGTH_SHORT).show();
}
});
gpQueue.add(gp_request);
super_1.setText(gp_market[0]);
return view;
}
}
但是文字是空的。什么是正确的方法?
答案 0 :(得分:4)
你在TextView上有任何ID吗? 试试这个:
MainActivity.java
String[] name_array = new String[2];
name_array[0]="test";
TextView textView = (TextView)findViewById(R.id.txt);
textView.setText(name_array[0]);
activity_main.xml中
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txt"/>