我试图在onCreate里面的主要活动中调用一个片段(Menu Fragment)。但它抛出错误(解决了问题) 附加问题 - >调用片段时,在获取数据时布局为空。我在frameLayout中调用它。
以下是main.xml的 Home.xml - &gt;菜单片段布局 这是Main.java我试图用onCreate方法中的片段替换。 这是MenuFragment.java类<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">
<!-- The main content view -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"/>
<!-- The navigation drawer -->
<ListView android:id="@+id/list_view"
android:layout_width="320dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@color/grey"
android:dividerHeight="0dp"
android:background="#000000"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/homeListView"
android:background="#FFFFFF"
android:divider="@color/grey"
android:dividerHeight="1dp">
</ListView>
</android.support.v4.widget.DrawerLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Topic"
android:textSize="30dp"
android:textColor="#000000"
android:fontFamily="sans-serif"
android:id="@+id/topic"
android:background="#ffffff"
android:padding="10dp"
android:textStyle="bold"
android:visibility="gone"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/homeListView"
android:background="#FFFFFF"
android:divider="@color/grey"
android:dividerHeight="1dp">
</ListView>
</LinearLayout>
public class Main extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mDrawerMenu;
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTitle = mDrawerTitle = getTitle();
mDrawerMenu = getResources().getStringArray(R.array.menu);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_view);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.custom_menu_list, mDrawerMenu));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
//Call Fragment
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MenuFragment fragment = new MenuFragment();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
//Action bar on item click events
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action buttons
switch(item.getItemId()) {
case R.id.menu_icon:
// create intent to perform web search for this planet
Log.d("Hello","Menu clicked");
mDrawerLayout.openDrawer(mDrawerList);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
Log.d("Hello", String.valueOf(position));
//Get the option name and compare
String text = ((TextView) arg1.findViewById(android.R.id.text1)).getText().toString();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Bundle data = new Bundle();
data.putString("Topic",text);
if(position == 0){
Log.d("Click","Home Clicked");
MenuFragment fragment = new MenuFragment();
fragment.setArguments(data);
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.commit();
}
else if(position == 1){
Log.d("Click","News Clicked 2");
NewsFragment fragment = new NewsFragment();
fragment.setArguments(data);
fragmentTransaction.replace(R.id.content_frame, fragment, String.valueOf(position));
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
else if(position == 2){
Log.d("Click","Opinion Clicked");
OpinionFragment OpF = new OpinionFragment();
OpF.setArguments(data);
fragmentTransaction.replace(R.id.content_frame, OpF, String.valueOf(position));
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
else if(position == 3){
Log.d("Click","Features Clicked");
FeaturesFragment FeF = new FeaturesFragment();
FeF.setArguments(data);
fragmentTransaction.replace(R.id.content_frame, FeF, String.valueOf(position));
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
else if(position == 4){
Log.d("Click","Arts Clicked");
ArtsFragment ArtsF = new ArtsFragment();
ArtsF.setArguments(data);
fragmentTransaction.replace(R.id.content_frame, ArtsF, String.valueOf(position));
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
else if(position == 5){
Log.d("Click","Sports Clicked");
SportsFragment SportsF = new SportsFragment();
SportsF.setArguments(data);
fragmentTransaction.replace(R.id.content_frame, SportsF, String.valueOf(position));
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
else if(position == 6){
Log.d("Click","Opinion Clicked");
BlogsFragment BlogsF = new BlogsFragment();
BlogsF.setArguments(data);
fragmentTransaction.replace(R.id.content_frame, BlogsF, String.valueOf(position));
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
mDrawerLayout.closeDrawer(mDrawerList);
}
}
}
public class MenuFragment extends Fragment {
private ProgressDialog pDialog;// Progress Dialog
ListView newsList;
String my_url;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> postList; //Declare Array
private static String url = "http://wangeltmg.com/GKN_ADMIN/GET_POSTS/";
GetNews.CustomAdapter CA;
// JSON Node names
private static final String TAG_ID = "id";
private static final String POST_ALLPOSTS = "posts";
private static final String POST_ID = "ID";
private static final String POST_TITLE = "post_title";
private static final String POST_CONTENT = "post_content";
private static final String POST_DATE = "post_date";
private static final String GUID = "guid";
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.home, container, false);
newsList = (ListView) view.findViewById(R.id.homeListView);
TextView topic = (TextView) view.findViewById(R.id.topic);
postList = new ArrayList<HashMap<String, String>>();
//Get arguments
Bundle args = getArguments();
String mytopic = args.getString("Topic");
newsList.setOnItemClickListener(new newsListClick());
getActivity().getActionBar().setTitle("GannonKnightNews");
//Set topic
topic.setText(mytopic.toUpperCase());
//Execute getContacts
new GetNews().execute();
return view;
}
public class newsListClick implements ListView.OnItemClickListener{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("News List","Clicked " + id);
String text = postList.get(position).get(GUID).toString();
String post_title = postList.get(position).get(POST_TITLE).toString();
String post_desc = postList.get(position).get(POST_CONTENT).toString();
Log.d("PostCOntent--->",post_desc);
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Bundle data = new Bundle();
data.putString("url", text);
data.putString(POST_TITLE, post_title);
data.putString(POST_CONTENT, post_desc);
SinglePost singleFrag = new SinglePost();
singleFrag.setArguments(data);
fragmentTransaction.replace(R.id.content_frame, singleFrag);
fragmentTransaction.commit();
}
}
//Async Task
private class GetNews extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Strings", "Checking Json");
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// contacts JSONArray
JSONArray posts = null;
// Getting JSON Array node
posts = jsonObj.getJSONArray(POST_ALLPOSTS);
// looping through All Contacts
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
Log.d("Post->",posts.getJSONObject(i).toString());
String id = c.getString(POST_ID);
Log.d("Post->ID",id);
String post_title = c.getString(POST_TITLE);
String post_content = c.getString(POST_CONTENT);
String guid = c.getString(GUID);
Log.d("GUID->",guid);
String post_date = c.getString(POST_DATE);
//String gender = c.getString(TAG_GENDER);
// tmp hashmap for single post
HashMap<String, String> post = new HashMap<String, String>();
// adding each child node to HashMap key => value
post.put(POST_ID, id);
post.put(POST_TITLE, post_title);
post.put(POST_CONTENT, post_content);
post.put(GUID, guid);
post.put(POST_DATE, post_date);
post.put("ListCount",String.valueOf(i));
// adding contact to contact list
postList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// Updating parsed JSON data into ListView
/*
ListAdapter adapter = new SimpleAdapter(getActivity(), postList, R.layout.list_item,
new String[] { POST_TITLE,POST_CONTENT, GUID },
new int[] {R.id.email, R.id.mobile, R.id.guid });
newsList.setAdapter(adapter);
*/
CA = new CustomAdapter( getActivity(), R.layout.list_item, postList);
newsList.setAdapter(CA);
}
public class CustomAdapter extends ArrayAdapter<HashMap<String, String>>{
private final ArrayList<HashMap<String, String>> objects;
public CustomAdapter(Context context, int resource, ArrayList<HashMap<String, String>> objects) {
//something is wrong with super
super(context, resource, objects);
inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.objects = objects;
}
@Override
public int getItemViewType(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup Parent){
//convertView = new ImageView();
//System.out.println("getView " + position + " " + convertView + " type = " + type);
if(convertView == null){
convertView = inflater.inflate(R.layout.list_item,null);
}
android.widget.ImageView postImage = (android.widget.ImageView) convertView.findViewById(R.id.img);
int getListPos = newsList.getFirstVisiblePosition();
//i set the count starting 0 and saved in the hashmap array
//to compare the first result with the first position of listview
int count = Integer.parseInt(objects.get(position).get("ListCount"));
my_url = objects.get(position).get(GUID);
if(getListPos == count) {
//LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_header,null);
TextView HeaderText = (TextView) convertView.findViewById(R.id.headertext);
TextView HeaderContent = (TextView) convertView.findViewById(R.id.headercontent);
TextView HeaderDate = (TextView) convertView.findViewById(R.id.header_date);
HeaderText.setText(objects.get(position).get(POST_TITLE).toUpperCase());
HeaderDate.setText(objects.get(position).get(POST_DATE));
HeaderContent.setText(objects.get(position).get(POST_CONTENT));
if(objects.get(position).get(GUID).equals("NULL")) {
postImage.setImageResource(R.drawable.default_bg);
}else{
new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
}
}
else{
//CHoose list item
//LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item,null);
TextView thisview = (TextView) convertView.findViewById(R.id.email);
TextView postContent = (TextView) convertView.findViewById(R.id.mobile);
thisview.setText(objects.get(position).get(POST_TITLE).toUpperCase());
postContent.setText(objects.get(position).get(POST_CONTENT));
if(objects.get(position).get(GUID).equals("NULL")) {
postImage.setImageResource(R.drawable.default_bg);
}else{
new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
}
}
return convertView;
}
}//Custom Adapter
}//END getnews Async Task
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}//
}
答案 0 :(得分:1)
你应该改变
String text = ((TextView) arg1.findViewById(android.R.id.text1)).getText().toString();
到
String text = ((TextView) arg1.findViewById(R.id.text1)).getText().toString();
您的Textview
ID为text1
。你正在尝试使用android.R.id.text1
。
这可能是您遇到问题的原因之一。
答案 1 :(得分:0)
与日志一样:
空对象上的android.os.Bundle.getString(java.lang.String)' 参考
第一次Main
活动开始在MenuFragment
中添加onCreate
片段而不传递任何带有Topic
密钥的Bundle。
因此修复此错误要么在onCreate
方法中添加片段时使用Bundle传递一些值,要么在null
中添加onCreateView
来检查从getArguments()
收到的Bundle,然后再调用任何值方法。例如:
String mytopic="";
Bundle args = getArguments();
if(args!=null)
mytopic = args.getString("Topic");