我收到编译时错误:
第91行 The method replace(int, Fragment, String) in the type FragmentTransaction is not applicable for the arguments (int, VideoListFragment, String)
VideoActivity.java:
package com.sit.loco.activity;
import android.support.v4.app.Fragment;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.loco.android.R;
import com.sit.loco.frgment.VideoListFragment;
public class VideoActivity extends SherlockFragmentActivity
implements ActionBar.OnNavigationListener, VideoListFragment.OnVideoSelectedListener{
// create object of ActionBar and VideoListFragment
ActionBar actionbar;
VideoListFragment videoListFrag;
int selectedItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
selectedItem = itemPosition;
// create object of VideoListFragment and send data position to that fragment
videoListFrag = new VideoListFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", itemPosition);
videoListFrag.setArguments(bundle);
// call video list fragment with new data
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, videoListFrag, "VIDEO_LIST_FRAGMENT")
.commit(); ---->Error at Line 91
return true;
}
}
MyFragmentPagerAdapter.java:
第68行 Type mismatch: cannot convert from VideoListFragment to Fragment
package com.sit.loco.provider;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 6;
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
/** This method will be invoked when a page is requested to create */
@Override
public Fragment getItem(int arg0) {
Bundle data = new Bundle();
switch (arg0) {
case 4:
VideoListFragment videoList = new VideoListFragment();
data.putInt("position", arg0);
videoList.setArguments(data);
return videoList; ---->Error at Line 68
}
return null;
}
/** Returns the number of pages */
@Override
public int getCount() {
return PAGE_COUNT;
}
}
修改
VideoListFragment.java:
package com.sit.loco.frgment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.loco.android.R;
import com.sit.loco.provider.VideoListAdapter;
public class VideoListFragment extends SherlockFragmentActivity {
OnVideoSelectedListener mCallback;
boolean loadingMore = false;
// create string variables
String YOUTUBE_USERNAME = "";
private String YOUTUBE_API = "http://gdata.youtube.com/feeds/api/users/"+YOUTUBE_USERNAME+"/uploads?alt=jsonc" +
"&v=2"+
"&start-index=1"+
"&max-results=10";
// create object of views
ListView list;
ProgressBar prgLoading;
Button btnRefresh;
Button btnLoadMore;
// create variable to get position, connection status, resources, and channel username
int position;
boolean isConnect = true;
Resources res;
String[] ChannelUsername;
// create object of custom adapter
VideoListAdapter vla;
// create arraylist variables
ArrayList<HashMap<String, String>> menuItems;
ProgressDialog pDialog;
// flag for current page
int current_page = 1;
int previous_page;
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_THUMBNAIL = "thumbnail";
static final String KEY_DURATION = "duration";
// create interface listener
public interface OnVideoSelectedListener{
public void onVideoSelected(String ID);
}
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_list);
// connect view objects and view id on xml
list = (ListView)findViewById(R.id.list);
// prgLoading = (ProgressBar) v.findViewById(R.id.prgLoading);
btnRefresh = (Button)findViewById(R.id.btnRefresh);
menuItems = new ArrayList<HashMap<String, String>>();
// get value that passed from previous page
Bundle bundle = this.getArguments();
position = bundle.getInt("position", 0);
// get channel username and put selected channel to youtube api
res = getActivity().getResources();
ChannelUsername = res.getStringArray(R.array.channel_username);
YOUTUBE_USERNAME = ChannelUsername[position];
YOUTUBE_API = "http://gdata.youtube.com/feeds/api/users/"+YOUTUBE_USERNAME+"/uploads?alt=jsonc" +
"&v=2"+
"&start-index=1"+
"&max-results=10";
// create LoadMore button
btnLoadMore = new Button(getActivity());
btnLoadMore.setBackgroundResource(R.drawable.btn_default_holo_light);
btnLoadMore.setText(getString(R.string.load_more));
// adding load more button to lisview at bottom
list.addFooterView(btnLoadMore);
new loadFirstListView().execute();
// listener to handle load more buttton when clicked
btnLoadMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Starting a new async task
isConnect = true;
new loadMoreListView().execute();
}
});
// listener to handle list when clicked
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
HashMap<String, String> item = new HashMap<String, String>();
item = menuItems.get(position);
mCallback.onVideoSelected(item.get("id"));
list.setItemChecked(position, true);
}
});
// listener to handle refresh button when clicked
btnRefresh.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
isConnect = true;
new loadFirstListView().execute();
}
});
}
private Bundle getArguments() {
// TODO Auto-generated method stub
return null;
}
private Context getActivity() {
// TODO Auto-generated method stub
return null;
}
public void onAttach(Fragment activity) {
super.onAttachFragment(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception.
try {
mCallback = (OnVideoSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
// load first 10 videos
private class loadFirstListView extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(
getActivity());
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
private Context getActivity() {
// TODO Auto-generated method stub
return null;
}
protected Void doInBackground(Void... unused) {
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
// Perform a GET request to YouTube for a JSON list of all the videos by a specific user
HttpUriRequest request = new HttpGet(YOUTUBE_API);
// Get the response that YouTube sends back
HttpResponse response = client.execute(request);
// Convert this response into an inputstream for the parser to use
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
//BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
JSONObject json = new JSONObject(str);
JSONObject dataObject = json.getJSONObject("data"); // this is the "data": { } part
JSONArray items = dataObject.getJSONArray("items"); // this is the "items: [ ] part
for (int i = 0; i < items.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject youtubeObject = items.getJSONObject(i);
map.put(KEY_ID, youtubeObject.getString("id")); // id not using any where
map.put(KEY_TITLE, youtubeObject.getString("title"));
map.put(KEY_THUMBNAIL, youtubeObject.getJSONObject("thumbnail").getString("hqDefault"));
String duration = secondToTime(youtubeObject.getInt("duration"));
map.put(KEY_DURATION, duration);
// adding HashList to ArrayList
menuItems.add(map);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
isConnect = false;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (null);
}
protected void onPostExecute(Void unused) {
// closing progress dialog
pDialog.dismiss();
if(isAdded()){
if(isConnect){
btnRefresh.setVisibility(View.GONE);
// Getting adapter
vla = new VideoListAdapter(getActivity(), menuItems);
list.setAdapter(vla);
}else{
btnRefresh.setVisibility(View.VISIBLE);
Toast.makeText(getActivity(), getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
}
}
}
}
// load more videos
private class loadMoreListView extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(
getActivity());
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(Void... unused) {
// store previous value of current page
previous_page = current_page;
// increment current page
current_page += 10;
YOUTUBE_API = "http://gdata.youtube.com/feeds/api/users/"+YOUTUBE_USERNAME+"/uploads?alt=jsonc" +
"&v=2"+
"&start-index="+current_page+
"&max-results=10";
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
// Perform a GET request to YouTube for a JSON list of all the videos by a specific user
HttpUriRequest request = new HttpGet(YOUTUBE_API);
// Get the response that YouTube sends back
HttpResponse response = client.execute(request);
// Convert this response into an inputstream for the parser to use
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
//BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
JSONObject json = new JSONObject(str);
JSONObject dataObject = json.getJSONObject("data"); // this is the "data": { } part
JSONArray items = dataObject.getJSONArray("items"); // this is the "items: [ ] part
for (int i = 0; i < items.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject youtubeObject = items.getJSONObject(i);
map.put(KEY_ID, youtubeObject.getString("id")); // id not using any where
map.put(KEY_TITLE, youtubeObject.getString("title"));
map.put(KEY_THUMBNAIL, youtubeObject.getJSONObject("thumbnail").getString("hqDefault"));
String duration = secondToTime(youtubeObject.getInt("duration"));
map.put(KEY_DURATION, duration);
// adding HashList to ArrayList
menuItems.add(map);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
isConnect = false;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (null);
}
protected void onPostExecute(Void unused) {
// closing progress dialog
pDialog.dismiss();
if(isConnect){
// get listview current position - used to maintain scroll position
int currentPosition = list.getFirstVisiblePosition();
btnRefresh.setVisibility(View.GONE);
// Appending new data to menuItems ArrayList
vla = new VideoListAdapter(
getActivity(),
menuItems);
list.setAdapter(vla);
// Setting new scroll position
list.setSelectionFromTop(currentPosition + 1, 0);
}else{
if(menuItems != null){
current_page = previous_page;
btnRefresh.setVisibility(View.GONE);
}else{
btnRefresh.setVisibility(View.VISIBLE);
}
Toast.makeText(getActivity(), getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
}
}
private Context getActivity() {
// TODO Auto-generated method stub
return null;
}
}
// method to convert second to hours, minutes, and seconds
String secondToTime(int duration){
String time = "";
String Hours = "";
String Minutes = "";
String Seconds = "";
double hours = 0.0;
double minutes = 0.0;
double seconds = 0.0;
DecimalFormat df = new DecimalFormat("#.####");
hours = duration / 3600;
minutes = (duration % 3600) /60;
seconds = duration % 60;
if((hours < 10) && (hours > 0)){
Hours = "0" + df.format(hours);
}else if(hours == 0){
Hours = "00";
}else{
Hours = df.format(hours);
}
if((minutes < 10) && (minutes > 0)){
Minutes = "0" + df.format(minutes);
}else if(minutes == 0){
Minutes = "00";
}else{
Minutes = df.format(minutes);
}
if((seconds < 10) && (seconds > 0)){
Seconds = "0" + df.format(seconds);
}else if(seconds == 0){
Seconds = "00";
}else{
Seconds = df.format(seconds);
}
time = Hours +":"+Minutes+":"+Seconds;
return time;
}
public boolean isAdded() {
// TODO Auto-generated method stub
return false;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
vla.imageLoader.clearCache();
Log.d("clear cache", "clear cache");
}
public void setArguments(Bundle data) {
// TODO Auto-generated method stub
}
}
我花了很多时间来解决这些错误。但我不知道如何解决这个编译错误。任何人都可以帮我解决这个问题。谢谢。
答案 0 :(得分:2)
您的VideoListFragment
扩展了SherlockFragmentActivity
类,但应该扩展Fragment
。
import android.support.v4.app.Fragment;
public class VideoListFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.fragment_list, container, false);
list = (ListView)view .findViewById(R.id.list);
btnRefresh = (Button)view .findViewById(R.id.btnRefresh);
return view;
}