为什么Android Toast没有显示?

时间:2019-03-15 07:52:29

标签: android toast

我在获取Toast上遇到问题

public class LiveMatch extends Fragment {

    private List<Items_list> matches;

    private static final String URL="https://www.cricbuzz.com/match-api/livematches.json";

    private String recent_match;


    View v;

    public LiveMatch() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.live, container, false);

        return v;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        matches = new ArrayList<>();
        final StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONArray live_match = new JSONArray(response);
                    Toast.makeText(v.getContext(),live_match.length(),Toast.LENGTH_LONG).show();
                    for (int i = 0; i < live_match.length(); i++) {
                        JSONObject object = live_match.getJSONObject(i);

                        recent_match = object.getString("mathes");

                        RecyclerView recyclerView = v.findViewById(R.id.recycl);
                        RecylerAddapter recylerAddapter = new RecylerAddapter(getContext(), matches);
                        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                        recyclerView.setAdapter(recylerAddapter);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(v.getContext(), error.toString(), Toast.LENGTH_SHORT).show();
                    }
                });

        Volley.newRequestQueue(Objects.requireNonNull(getContext())).add(stringRequest);
}
}

5 个答案:

答案 0 :(得分:1)

吐司只能在弯针线(例如主线)上显示。我的猜测是Volley的回调在工作线程上运行。

从主线程显示吐司面包:

getActivity().runOnUiThread({
    Toast.makeText(...).show()
})

我正在使用Java 8 lambda表示法,但是您可以将其改编为Runnable

话虽如此,也请阅读所有其他答案。

答案 1 :(得分:0)

您必须在“片段”中使用getActivity()getContext()来获取默认上下文并使用它。 非常干净v.getContext()并调用上述方法之一

答案 2 :(得分:0)

Toast makeText方法已重载,可以通过资源ID进行加载

  

makeText(上下文上下文,int resId,int持续时间)

或传递文字以显示

  

makeText(上下文上下文,CharSequence文本,int持续时间)

如果使用整数live_match.length()加载,Android会尝试加载所需的资源,但找不到该资源,因此不会显示Toast。为了达到目标,您必须按照评论中的说明将该整数转换为字符串(实际上是CharSequence)。

Toast.makeText(getActivity(), String.valueOf(live_match.length()), Toast.LENGTH_LONG).show();

如果这不起作用,请确保您可以从那里触摸主线程,我认为您是在不允许触摸用户界面的后台线程中加载Toast的

答案 3 :(得分:0)

问题出在解析JSON响应中。

Web服务(API)响应来自JSONObject,而您正在JSONArray中对其进行处理。
查看Livestream URL的响应

enter image description here

更正您的处理响应代码,它将起作用。

请注意,由于match对象包含JSONObject,因此必须使用Iterator迭代循环来获取值。

如下更新您的onResponse方法:

@Override
public void onResponse(String response) {
    try {
        JSONObject jsonObject = new JSONObject(response);
        Log.e("Response: ", jsonObject.toString());
        JSONObject objMatch = jsonObject.optJSONObject("matches");
        Iterator<String> iterator = objMatch.keys();
        int counter = 0;

        while (iterator.hasNext()) {
            String key = iterator.next();
            try {
                JSONObject value = objMatch.getJSONObject(key);
                Log.e("Value: ", value.toString());
                // Here you have to add values in Items_list  and then after add it in matches list
                counter++;
            } catch (JSONException e) {
                // Something went wrong!
            }
        }
        Toast.makeText(getActivity(), "Total Records: " + counter, Toast.LENGTH_LONG).show();
        // After competition of iterator loop, you have to set that List in RecyclerView Adapter here
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

答案 4 :(得分:-2)

Toast仅接受CharSequence“ String”。将您的值转换为字符串,您将可以看到吐司。 String.Valueof(您的值)。 live_match.length()可能是一个整数。在Fragment中,尝试getActivity()

public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
    return makeText(context, null, text, duration);
}
相关问题