Jurkam
Jurkam

Reputation: 11

How to set String array into TextView?

I'm trying set the string of one array into a TextView. I'm trying something like this:

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;
    } 
}

But the text is empty. What is the right way to do it?

Upvotes: 1

Views: 2068

Answers (1)

Maor
Maor

Reputation: 3430

Do you have any id on TextView? try this :


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"/>

Upvotes: 4

Related Questions