Java 即使编译时没有错误,JSON查询也不会显示项

Java 即使编译时没有错误,JSON查询也不会显示项,java,android,android-studio,youtube-api,Java,Android,Android Studio,Youtube Api,我刚刚开始学习android,所以现在我的目标是使用Youtube API创建一个应用程序,该应用程序具有多种功能,但其中一项功能(如搜索视频并在屏幕上列出视频)不起作用,也没有错误,但当我按下搜索按钮时,什么也没有发生。这是主类的代码 import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.WindowMa

我刚刚开始学习android,所以现在我的目标是使用Youtube API创建一个应用程序,该应用程序具有多种功能,但其中一项功能(如搜索视频并在屏幕上列出视频)不起作用,也没有错误,但当我按下搜索按钮时,什么也没有发生。这是主类的代码


import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.app.youtubedownloader.Adapter.MyAdapter;
import com.app.youtubedownloader.Model.VideoDetails;
import com.google.android.youtube.player.YouTubeBaseActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    String API_KEY = "here is my api key";
    ListView listView;
    ArrayList<VideoDetails> videoDetailsArrayList;
    MyAdapter myadapter;
    String url = "https://www.googleapis.com/youtube/v3/search?";
    String part = "snippet";
    ImageButton searchbtn;
    EditText searchfield;
    String keySearch;
    Integer maxResults = 10;
    String order = "title";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = findViewById(R.id.listvideos);
        videoDetailsArrayList = new ArrayList<>();
        myadapter = new MyAdapter(MainActivity.this, videoDetailsArrayList);
        searchfield = findViewById(R.id.searchfield);
        searchbtn = findViewById(R.id.searchbtn);

        searchbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                keySearch =  searchfield.getText().toString();
                displayVideos();
            }
        });





    }

    public void displayVideos(){
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

        url = "https://www.googleapis.com/youtube/v3/search?" + "part=" + part + "&q=" + keySearch + "&maxResults=3" + "&order=" + order + "&key=" + API_KEY;

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                try{
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray jsonArray = jsonObject.getJSONArray("items");

                    for(int i=0; i<jsonArray.length(); i++){
                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                        JSONObject jsonVideoId = jsonObject1.getJSONObject("id");

                        JSONObject jsonObjectSnippet = jsonObject1.getJSONObject("snippet");

                        JSONObject jsonObjectDefault = jsonObjectSnippet.getJSONObject("thumbnails").getJSONObject("medium");

                        String video_id = jsonVideoId.getString("videoId");

                        VideoDetails vd = new VideoDetails();


                        vd.setVideoID(video_id);
                        vd.setTitle(jsonObjectSnippet.getString("title"));
                        vd.setDescription(jsonObjectSnippet.getString("description"));
                        vd.setUrl(jsonObjectDefault.getString("url"));

                        videoDetailsArrayList.add(vd);


                    }

                    listView.setAdapter(myadapter);
                    myadapter.notifyDataSetChanged();

                } catch(JSONException e){
                    e.printStackTrace();
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
            }
        });


        requestQueue.add(stringRequest);


    }

}
我认为不需要XML文件。非常感谢。 另外,我试着用邮递员测试我的url请求,结果成功了。 编辑:


哦,我想我知道了。看起来您的响应返回正常,在处理每个“项”的“for”循环时,您正在获取对象“id”,在该对象内部,您正在查找“videoId”。这是很好的,除了三个结果中的最后一个,在你的邮递员结果中是这样的:

{
 "kind": "youtube#searchResult",
 "etag": "\"p4VTdlkQv3HQeTEaXgvLePAydmU/sy1iQ191YnpipX54MZQ-Z-bd2YU\"",
 "id": {
  "kind": "youtube#channel",
  "channelId": "UCUd0dDUCXsjBPnG1qeUHZLw"
 },
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
JSONObject jsonId = jsonObject1.getJSONObject("id");
String video_id = "";
String channel_id = "";


try {

   video_id = jsonId.getString("videoId");

}catch(JSONException e) {
   channel_id = jsonId.getString("channelId");
}
它有一个channelId而不是videoId。您应该做的是将每个JSON表达式捕获到它自己的try/catch块中,这样一个错误的响应就不会阻止整个结果。大概是这样的:

{
 "kind": "youtube#searchResult",
 "etag": "\"p4VTdlkQv3HQeTEaXgvLePAydmU/sy1iQ191YnpipX54MZQ-Z-bd2YU\"",
 "id": {
  "kind": "youtube#channel",
  "channelId": "UCUd0dDUCXsjBPnG1qeUHZLw"
 },
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
JSONObject jsonId = jsonObject1.getJSONObject("id");
String video_id = "";
String channel_id = "";


try {

   video_id = jsonId.getString("videoId");

}catch(JSONException e) {
   channel_id = jsonId.getString("channelId");
}
您可以尝试添加更多日志记录,然后在运行代码时,通过查看日志至少可以知道发生了什么:

    public void displayVideos(){
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

        url = "https://www.googleapis.com/youtube/v3/search?" + "part=" + part + "&q=" + keySearch + "&maxResults=3" + "&order=" + order + "&key=" + API_KEY;

        Log.i("My App", "url=" + url);

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                Log.i("My App", "response=" + response);

                try{
                    Log.i("My App", "before jsonObject");
                    JSONObject jsonObject = new JSONObject(response);
                    Log.i("My App", "after jsonObject:" + jsonObject.toString());

                    Log.i("My App", "before jsonArray");
                    JSONArray jsonArray = jsonObject.getJSONArray("items");
                    Log.i("My App", "after jsonArray: count=" + jsonArray.length());

                    for(int i=0; i<jsonArray.length(); i++){
                       Log.i("My App", "before jsonObject1");
                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                       Log.i("My App", "after jsonObject1:" + jsonObject1.toString());

                        Log.i("My App", "before jsonVideoId");
                        JSONObject jsonVideoId = jsonObject1.getJSONObject("id");
                        Log.i("My App", "after jsonVideoId:" + jsonVideoId.toString());    

...  (your other code here)

                        Log.i("My App", "before videoId");  
                        String video_id = jsonVideoId.getString("videoId");
                        Log.i("My App", "after videoId:" + video_id); 

... (your other code here)   

                    }

                    listView.setAdapter(myadapter);
                    myadapter.notifyDataSetChanged();

                } catch(JSONException e){
                    Log.e("My App", e.getLocalizedMessage());
                    e.printStackTrace();
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
               Log.e("My App", error.getMessage());
                Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
            }
        });


        requestQueue.add(stringRequest);


    }

}

如果尚未执行此操作,则应在onResponse覆盖中“try”下的第一条指令上设置断点,并在同一覆盖中的“catch”中的指令上设置断点。以及响应中的第一条指令。显示onResponse中返回的字符串或返回的任何错误消息。在字符串连接混淆api键后,还应该向我们显示url。您的意思是我应该添加什么断点?而且,没有返回错误,Response.ErrorListener中的toast没有返回,因为Response上没有错误。连接后的URL是这样的https://www.googleapis.com/youtube/v3/search?part=snippet&q=Funnyvideos&order=title&maxResults=3&key=keyIn 在onResponse覆盖中,应该突出显示这行代码JSONObject JSONObject=new JSONObject response;然后选择运行菜单,然后切换行断点。这将在最左边的快捷方式的行号旁边放置一个红点,只需点击行号的右侧,红点就会出现。这将导致代码在执行过程中暂停,以便显示响应字符串中返回的内容,或者添加指令Log.iMy App,response:+response;在catch e.printStackTrace中执行相同的操作;或Log.eMy应用程序,例如getLocalizedMessage;运行应用程序时,请确保单击“运行调试看起来像瓢虫”“不运行看起来像三角形”,否则,您的代码不会在断点处停止。我编辑了问题并在响应字符串中添加了我得到的内容,搜索FunnyVideos时,我尝试使用上面的代码序列,但也没有发生任何事情,我还试图修改部分forint I=0;当我尝试输入I=0时,输入I;我不记得是jsonArray.length还是jsonArray.count,但这是正确的选择。如果你说i<1,你只能得到数组中的第一个元素。我想如果你把这个添加到你的查询字符串&type=video中,你就不会得到你目前在第三个结果中得到的“channel”结果。我知道如果我使用iTried来使用&type=video,什么都不会发生,搜索时仍然没有任何提示,而且jsonarray.count也不起作用。
    public void displayVideos(){
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

        url = "https://www.googleapis.com/youtube/v3/search?" + "part=" + part + "&q=" + keySearch + "&maxResults=3" + "&order=" + order + "&key=" + API_KEY;

        Log.i("My App", "url=" + url);

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                Log.i("My App", "response=" + response);

                try{
                    Log.i("My App", "before jsonObject");
                    JSONObject jsonObject = new JSONObject(response);
                    Log.i("My App", "after jsonObject:" + jsonObject.toString());

                    Log.i("My App", "before jsonArray");
                    JSONArray jsonArray = jsonObject.getJSONArray("items");
                    Log.i("My App", "after jsonArray: count=" + jsonArray.length());

                    for(int i=0; i<jsonArray.length(); i++){
                       Log.i("My App", "before jsonObject1");
                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                       Log.i("My App", "after jsonObject1:" + jsonObject1.toString());

                        Log.i("My App", "before jsonVideoId");
                        JSONObject jsonVideoId = jsonObject1.getJSONObject("id");
                        Log.i("My App", "after jsonVideoId:" + jsonVideoId.toString());    

...  (your other code here)

                        Log.i("My App", "before videoId");  
                        String video_id = jsonVideoId.getString("videoId");
                        Log.i("My App", "after videoId:" + video_id); 

... (your other code here)   

                    }

                    listView.setAdapter(myadapter);
                    myadapter.notifyDataSetChanged();

                } catch(JSONException e){
                    Log.e("My App", e.getLocalizedMessage());
                    e.printStackTrace();
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
               Log.e("My App", error.getMessage());
                Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
            }
        });


        requestQueue.add(stringRequest);


    }

}