我正在研究Navigaion Drawer,我在Fragment Activity中插入了ListActivity,并将Fragment更改为ListFragment。但我仍然得到错误。请注意logcat,让我知道如何纠正错误。
我想在Fragment中看到ListActivity。
FragmentOne.java
public class FragmentOne extends ListFragment {
public boolean net;
ImageView ivIcon;
TextView tvItemName;
public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";
final static String LOG_TAG = "rnc";
ListView listview;
public FragmentOne() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.twit_list, container,
false);
downloadTweets();
listview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String lst_txt = parent.getItemAtPosition(position).toString().trim();
System.out.println("Display text"+lst_txt );
// Launching new Activity on selecting single List Item
Intent i = new Intent(FragmentOne.this.getActivity(), SingleListItem.class);
// sending data to new activity
i.putExtra("product",lst_txt );
startActivity(i);
}
});
return view;
}
public void downloadTweets() {
TwitterUser o = new TwitterUser();
String m = o.getValue();
System.out.println("Kida "+m);
listview = this.getListView();
String ScreenName =m;
ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadTwitterTask().execute(ScreenName);
} else {
Log.v(LOG_TAG, "No network connection available.");
}
}
// Uses an AsyncTask to download a Twitter user's timeline
private class DownloadTwitterTask extends AsyncTask<String, Void, String> {
final static String CONSUMER_KEY = "kJ9cZesXIjdztc6fubuhygvkqU";
final static String CONSUMER_SECRET = "njinbjinjimjimionuiXGonaIcWTG";
final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
private ProgressDialog progressDialog;
@Override
// can use UI thread here
protected void onPreExecute() {
try{
progressDialog = new ProgressDialog(FragmentOne.this.getActivity(),AlertDialog.THEME_HOLO_DARK);
progressDialog.setIndeterminate(true);
progressDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.loader_2));
progressDialog.setMessage("Please Wait ! Unwrapping Something for You...");
progressDialog.show();
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
}
catch(Exception e)
{
this.progressDialog.dismiss();
Toast.makeText(getActivity().getApplicationContext(),e.toString(), Toast.LENGTH_LONG).show();
}
}
@Override
protected String doInBackground(String... screenNames) {
String result = null;
if (screenNames.length > 0) {
result = getTwitterStream(screenNames[0]);
}
return result;
}
// onPostExecute convert the JSON results into a Twitter object (which is an Array list of tweets
@Override
protected void onPostExecute(String result) {
Twitter twits = jsonToTwitter(result);
// lets write the results to the console as well
for (Tweet tweet : twits) {
Log.i(LOG_TAG, tweet.getText());
}
/// ArrayAdapter<Tweet> al = new ArrayAdapter<Tweet>();
// listview.setAdapter(new DataAdapter(MainActivity.this,al.toArray(new String[al.size()])));
System.out.println("Kamina "+ twits);
// send the tweets to the adapter for rendering
// ArrayAdapter adapter = new ArrayAdapter<Tweet>(activity, android.R.layout.simple_list_item_1, twits);
// setListAdapter(adapter);
ArrayAdapter<Tweet> adapter = new ArrayAdapter<Tweet>(getActivity().getBaseContext(),R.layout.customgrid,R.id.texts, twits);
setListAdapter(adapter);
// ArrayAdapter myAdapter = new ArrayAdapter (this,twits);
// setListAdapter(myAdapter);
// ArrayAdapter<String> ad = new ArrayAdapter<String>(context,R.layout.customgrid,arr);
// lst.setAdapter(ad);
this.progressDialog.dismiss();
}
// converts a string of JSON data into a Twitter object
private Twitter jsonToTwitter(String result) {
Twitter twits = null;
if (result != null && result.length() > 0) {
try {
Gson gson = new Gson();
twits = gson.fromJson(result, Twitter.class);
} catch (IllegalStateException ex) {
// just eat the exception
}
}
return twits;
}
// convert a JSON authentication object into an Authenticated object
private Authenticated jsonToAuthenticated(String rawAuthorization) {
Authenticated auth = null;
if (rawAuthorization != null && rawAuthorization.length() > 0) {
try {
Gson gson = new Gson();
auth = gson.fromJson(rawAuthorization, Authenticated.class);
} catch (IllegalStateException ex) {
// just eat the exception
}
}
return auth;
}
private String getResponseBody(HttpRequestBase request) {
StringBuilder sb = new StringBuilder();
try {
DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
String reason = response.getStatusLine().getReasonPhrase();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
String line = null;
while ((line = bReader.readLine()) != null) {
sb.append(line);
}
} else {
sb.append(reason);
}
} catch (UnsupportedEncodingException ex) {
} catch (ClientProtocolException ex1) {
} catch (IOException ex2) {
}
return sb.toString();
}
private String getTwitterStream(String screenName) {
String results = null;
// Step 1: Encode consumer key and secret
try {
// URL encode the consumer key and secret
String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");
// Concatenate the encoded consumer key, a colon character, and the
// encoded consumer secret
String combined = urlApiKey + ":" + urlApiSecret;
// Base64 encode the string
String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);
// Step 2: Obtain a bearer token
HttpPost httpPost = new HttpPost(TwitterTokenURL);
httpPost.setHeader("Authorization", "Basic " + base64Encoded);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
String rawAuthorization = getResponseBody(httpPost);
Authenticated auth = jsonToAuthenticated(rawAuthorization);
// Applications should verify that the value associated with the
// token_type key of the returned object is bearer
if (auth != null && auth.token_type.equals("bearer")) {
// Step 3: Authenticate API requests with bearer token
HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName+"&count=10");
// construct a normal HTTPS request and include an Authorization
// header with the value of Bearer <>
httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
httpGet.setHeader("Content-Type", "application/json");
// update the results with the body of the response
results = getResponseBody(httpGet);
}
} catch (UnsupportedEncodingException ex) {
} catch (IllegalStateException ex1) {
}
return results;
}
}
}
logcat的
12-17 07:04:10.588: E/AndroidRuntime(1667): FATAL EXCEPTION: main
12-17 07:04:10.588: E/AndroidRuntime(1667): java.lang.IllegalStateException: Content view not yet created
12-17 07:04:10.588: E/AndroidRuntime(1667): at android.app.ListFragment.ensureList(ListFragment.java:386)
12-17 07:04:10.588: E/AndroidRuntime(1667): at android.app.ListFragment.getListView(ListFragment.java:280)
12-17 07:04:10.588: E/AndroidRuntime(1667): at com.iamrajkaran.navigation.FragmentOne.downloadTweets(FragmentOne.java:112)
12-17 07:04:10.588: E/AndroidRuntime(1667): at com.iamrajkaran.navigation.FragmentOne.onCreateView(FragmentOne.java:77)
12-17 07:04:10.588: E/AndroidRuntime(1667): at android.app.Fragment.performCreateView(Fragment.java:1695)
12-17 07:04:10.588: E/AndroidRuntime(1667): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:885)
12-17 07:04:10.588: E/AndroidRuntime(1667): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
12-17 07:04:10.588: E/AndroidRuntime(1667): at android.app.BackStackRecord.run(BackStackRecord.java:682)
12-17 07:04:10.588: E/AndroidRuntime(1667): at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
12-17 07:04:10.588: E/AndroidRuntime(1667): at android.app.FragmentManagerImpl$1.run(FragmentManager.java:441)
12-17 07:04:10.588: E/AndroidRuntime(1667): at android.os.Handler.handleCallback(Handler.java:725)
12-17 07:04:10.588: E/AndroidRuntime(1667): at android.os.Handler.dispatchMessage(Handler.java:92)
12-17 07:04:10.588: E/AndroidRuntime(1667): at android.os.Looper.loop(Looper.java:137)
12-17 07:04:10.588: E/AndroidRuntime(1667): at android.app.ActivityThread.main(ActivityThread.java:5039)
12-17 07:04:10.588: E/AndroidRuntime(1667): at java.lang.reflect.Method.invokeNative(Native Method)
12-17 07:04:10.588: E/AndroidRuntime(1667): at java.lang.reflect.Method.invoke(Method.java:511)
12-17 07:04:10.588: E/AndroidRuntime(1667): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-17 07:04:10.588: E/AndroidRuntime(1667): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-17 07:04:10.588: E/AndroidRuntime(1667): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:3)
问题是您正在调用与UI相关的方法,如getListView(
),但视图还没有准备好。您应该使用方法onViewCreated()
:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.twit_list, container, false);
}
@Override
public View onViewCreated(View view, Bundle savedInstanceState) {
downloadTweets();
listview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
...
}
});
}
答案 1 :(得分:1)
您的问题是您没有正确初始化ListView
对象。
尝试以下方法:
View view = inflater.inflate(R.layout.twit_list, container,
false);
listview = (ListView) view.findViewById(android.R.list); //This is probably the id for your listview if you have defined it correctly
然后从listview = this.getListView();
方法中删除downloadTweets()
。
另一种可能性是将您的downloadTweets()
和setOnClickListener
移动到之后将被调用的方法,例如onStart
。
希望有所帮助