gpt4 book ai didi

android - 如何在 Android 中使用 JSON 在 ListView 中获取 youtube 缩略图?到目前为止我的代码 :

转载 作者:搜寻专家 更新时间:2023-11-01 08:56:27 26 4
gpt4 key购买 nike

尝试获取有关如何使用下面代码中提到的 url 中的所有标签的信息。

公共(public)类 YoutubeVideoMain 扩展 Activity {

ListView videolist;

ArrayList<String> videoArrayList = new ArrayList<String>();

ArrayAdapter<String> videoadapter;
Context context;

String feedURL = "https://gdata.youtube.com/feeds/api/users/twistedequations/uploads?v=2&alt=jsonc&start-index=1&max-results=5";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.youtubelist);
videolist = (ListView) findViewById(R.id.videolist);

videoadapter = new ArrayAdapter<String>(this, R.layout.video_list_item,
videoArrayList);

videolist.setAdapter(videoadapter);
VideoListTask loadertask = new VideoListTask();
loadertask.execute();
}

private class VideoListTask extends AsyncTask<Void, String, Void> {

ProgressDialog dialogue;

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dialogue.dismiss();

videoadapter.notifyDataSetChanged();
}

@Override
protected void onPreExecute() {
dialogue = new ProgressDialog(context);

dialogue.setTitle("Loading items..");
dialogue.show();
super.onPreExecute();

}

@Override
protected Void doInBackground(Void... params) {

HttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(feedURL);
try {
HttpResponse response = client.execute(getRequest);
StatusLine statusline = response.getStatusLine();
int statuscode = statusline.getStatusCode();

if (statuscode != 200) {

return null;
}

InputStream jsonStream = response.getEntity().getContent();

BufferedReader reader = new BufferedReader(
new InputStreamReader(jsonStream));

StringBuilder builder = new StringBuilder();
String line;

while ((line = reader.readLine()) != null) {

builder.append(line);

}
String jsonData = builder.toString();

JSONObject json = new JSONObject(jsonData);

JSONObject data = json.getJSONObject("data");

JSONArray items = data.getJSONArray("items");

for (int i = 0; i < items.length(); i++) {

JSONObject video = items.getJSONObject(i);

videoArrayList.add(video.getString("title"));

}

Log.i("YouJsonData:", jsonData);

} catch (ClientProtocolException e) {

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

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

e.printStackTrace();
}

return null;
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

我试图在 ListView 中获取缩略图,还试图在点击任何项目时打开一个新的视频播放器。上面的代码显示了带有视频标题的项目列表,但我也想向其中添加缩略图。

帮我解决这个问题。

最佳答案

我使用 Universal ImageL0ader 进行延迟加载。您下载并使用它或使用不同的技术。根据您的需要自定义以下内容。

  1. 使用 threadAsynctask 向 json 响应发出 http 请求。

  2. 解析响应并将其存储在列表中。

  3. 使用自定义适配器显示数据。

您还可以使用 Volley 库。

public class MainActivity extends Activity {

Button b;
ListView lv;
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> title = new ArrayList<String>();
ArrayList<String> thumb = new ArrayList<String>();
ProgressDialog pd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv= (ListView) findViewById(R.id.lv);
pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Loading..");
b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new TheTask().execute();
}

});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void getData()
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("https://gdata.youtube.com/feeds/api/users/twistedequations/uploads?v=2&alt=jsonc&start-index=1&max-results=5");

try
{
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity); // content will be consume only once

JSONObject json = new JSONObject(_response);

JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);

String title1 = jsonObject.getString("title");
title.add(title1);
String thumbUrl = jsonObject.getJSONObject("thumbnail").getString("sqDefault");
URL url1 = new URL(thumbUrl);
//Bitmap bmp = BitmapFactory.decodeStream(url1.openConnection().getInputStream());
thumb.add(thumbUrl);
String url;
try {

url = jsonObject.getJSONObject("player").getString("default");
msg.add(url);
} catch (JSONException ignore) {
}
}
}
catch(Exception e1)
{
e1.printStackTrace();
}

httpclient.getConnectionManager().shutdown();
}
class TheTask extends AsyncTask<Void,Void,Void>
{

@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
YouTubeAdapter you = new YouTubeAdapter(MainActivity.this,msg,title,thumb);
lv.setAdapter(you);
}

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd.show();
}

@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
getData();
return null;
}

}
}

public class YouTubeAdapter extends BaseAdapter{

Context mContext;
Intent intent;
LayoutInflater mInflater;
ArrayList<String> mVideo;
ArrayList<String> mTitle;
ArrayList<String> mThumb;
static DisplayImageOptions options;
static ImageLoader imageLoader;

public YouTubeAdapter(Context context,ArrayList<String> a,ArrayList<String> title,ArrayList<String> thumb) {
mContext=context;
mVideo=a;
mTitle = title;
mThumb= thumb;
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_launcher)
.resetViewBeforeLoading()
.cacheOnDisc()
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.bitmapConfig(Bitmap.Config.RGB_565)
.displayer(new FadeInBitmapDisplayer(300))
.build();

imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return mVideo.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(final int position, View arg1, ViewGroup arg2) {
ViewHolder vh;

if(arg1==null)
{
arg1=mInflater.inflate(R.layout.video, null);
vh= new ViewHolder();
vh.tv1=(TextView)arg1.findViewById(R.id.textView1);
vh.tv2=(TextView)arg1.findViewById(R.id.textView2);
vh.iv=(ImageView)arg1.findViewById(R.id.imageView1);
vh.pb = (ProgressBar) arg1.findViewById(R.id.pb);
arg1.setTag(vh);
}
else
{
vh= (ViewHolder)arg1.getTag();
}
vh.tv1.setText(mTitle.get(position));
vh.tv2.setText(mVideo.get(position));
display(vh.iv, mThumb.get(position), vh.pb);
return arg1;
}

static public void display(ImageView img, String url, final ProgressBar spinner)
{
imageLoader.displayImage(url, img, options, new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
spinner.setVisibility(View.VISIBLE);
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
spinner.setVisibility(View.GONE);


}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
}
@Override
public void onLoadingCancelled(String imageUri, View view) {

}

});
}
static class ViewHolder
{
TextView tv1;
TextView tv2;
ImageView iv;
ProgressBar pb;
}
}

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/lv"
android:layout_above="@+id/button1"
/>

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />

</RelativeLayout>

快照

enter image description here

关于android - 如何在 Android 中使用 JSON 在 ListView 中获取 youtube 缩略图?到目前为止我的代码 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18567613/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com