2016-10-29 90 views
1

我想將一個數組的字符串設置爲TextView。我試圖這樣的:如何將String數組設置爲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

你在哪裏把這些代碼?在'onCreate'? – firmanslash

+0

@firmanslash yep – Jurkam

+0

其實你的代碼沒有錯,你能顯示你的完整代碼嗎? – firmanslash

回答

4

TextView上有任何標識嗎? 試試這個:


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"/> 
相關問題