首先,非常感谢所有支持像我这样的新手。
我正在创建一个应用程序,其中我遵循以下场景: -
我希望按下后退按钮上的子类别片段,但它会显示空白屏幕。
我搜索了很多并且在过去3天里苦苦挣扎,但我无法弄清楚发生了什么。
请帮帮我。我在下面发布我的代码: -
HomeScreenActivity.java
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
public class HomeScreenActivity extends Activity implements
NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the
* navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in
* {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = HomeFragment.newInstance(position + 1);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment).commit();
}
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.home_screen, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
HomeFragment.java
import java.util.List;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
public class HomeFragment extends Fragment {
/**
* The fragment argument representing the section number for this fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Defining layout items.
**/
GridView gridView;
/**
* Returns a new instance of this fragment for the given section number.
*/
public static HomeFragment newInstance(int sectionNumber) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public HomeFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
ParikshaDbHelper parikshaDbHelper = ParikshaDbHelper.getInstance(getActivity().getApplicationContext());
SQLiteDatabase db = parikshaDbHelper.getWritableDatabase();
List<Category> categories = CategoryDao.getAllParents(db);
if(categories.size() > 0){
gridView = (GridView) rootView.findViewById(R.id.gridView1);
gridView.setAdapter(new GridViewAdapter(getActivity(),R.layout.grid_item, categories));
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Category category = (Category) parent.getItemAtPosition(position);
Fragment subCategoryFragment = SubcategoryFragment.newInstance(5);
if (subCategoryFragment != null) {
FragmentManager fragmentManager = getFragmentManager();
Bundle args = new Bundle();
args.putInt("catId", category.getCategoryId());
subCategoryFragment.setArguments(args);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, subCategoryFragment);
String randomName = MyStringRandomGen.generateRandomString();
fragmentTransaction.addToBackStack(randomName);
fragmentTransaction.commit();
}
}
});
}
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((HomeScreenActivity) activity).onSectionAttached(getArguments().getInt(
ARG_SECTION_NUMBER));
}
}
SubcategoryFragment.java
import java.util.List;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
public class SubcategoryFragment extends Fragment {
/**
* The fragment argument representing the section number for this fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
Integer category_id;
/**
* Defining layout items.
**/
GridView gridView;
/**
* Returns a new instance of this fragment for the given section number.
*/
public static SubcategoryFragment newInstance(int sectionNumber) {
SubcategoryFragment fragment = new SubcategoryFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public SubcategoryFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle bundle = this.getArguments();
category_id = bundle.getInt("catId");
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
ParikshaDbHelper parikshaDbHelper = ParikshaDbHelper.getInstance(getActivity().getApplicationContext());
SQLiteDatabase db = parikshaDbHelper.getWritableDatabase();
List<Category> categories = CategoryDao.getAllChildrens(db, category_id);
if(categories.size() > 0){
gridView = (GridView) rootView.findViewById(R.id.gridView1);
gridView.setAdapter(new GridViewAdapter(getActivity(),R.layout.grid_item, categories));
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Category category = (Category) parent.getItemAtPosition(position);
Fragment detailsFragment = DetailsFragment.newInstance(6);
if (detailsFragment != null) {
FragmentManager fragmentManager = getFragmentManager();
Bundle args = new Bundle();
args.putInt("catId", category.getCategoryId());
detailsFragment.setArguments(args);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, detailsFragment);
String randomName = MyStringRandomGen.generateRandomString();
fragmentTransaction.addToBackStack(randomName);
fragmentTransaction.commit();
}
}
});
}
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((HomeScreenActivity) activity).onSectionAttached(getArguments().getInt(
ARG_SECTION_NUMBER));
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("catId", category_id);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore last state for checked position.
category_id = savedInstanceState.getInt("catId");
}
}
}
DetailsFragment.java
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
public class DetailsFragment extends Fragment {
/**
* The fragment argument representing the section number for this fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
public ListView listView;
public TextView txtCatName;
public List<QuestAns> questAns;
public CustomListViewArrayAdapter adapter = null;
public Integer category_id;
/**
* Returns a new instance of this fragment for the given section number.
*/
public static DetailsFragment newInstance(int sectionNumber) {
DetailsFragment fragment = new DetailsFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public DetailsFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.e("DetailsFragment", "OnCreateView Called");
View rootView = inflater.inflate(R.layout.fragment_details, container, false);
listView = (ListView) rootView.findViewById(R.id.questListing);
txtCatName = (TextView) rootView.findViewById(R.id.txtCatName);
ParikshaDbHelper parikshaDbHelper = ParikshaDbHelper.getInstance(getActivity().getApplicationContext());
SQLiteDatabase db = parikshaDbHelper.getWritableDatabase();
Bundle bundle = this.getArguments();
category_id = bundle.getInt("catId");
Category category = CategoryDao.findById(db, category_id);
List<QuestAns> questAns = QuestAnsDao.getAllByCategories(db, category_id);
txtCatName.setText(category.getCategoryName());
if(questAns.size() > 0){
adapter = new CustomListViewArrayAdapter(getActivity()
.getApplicationContext(), R.layout.quesans_item,
questAns);
listView.setAdapter(adapter);
}else{
NetAsync();
}
return rootView;
}
public void NetAsync() {
new NetCheck().execute();
}
/**
* Async Task to check whether internet connection is working
**/
private class NetCheck extends AsyncTask<String, Void, Boolean> {
private ProgressDialog nDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
nDialog = new ProgressDialog(getActivity());
nDialog.setMessage("Loading..");
nDialog.setTitle("Checking Network");
nDialog.setIndeterminate(false);
nDialog.setCancelable(false);
nDialog.show();
}
@Override
protected Boolean doInBackground(String... args) {
/**
* Gets current device state and checks for working internet
* connection by trying Google.
**/
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url
.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
protected void onPostExecute(Boolean th) {
if (th == true) {
nDialog.dismiss();
new GetQuesAns().execute();
} else {
nDialog.dismiss();
}
}
}
private class GetQuesAns extends AsyncTask<String, Void, JSONObject> {
/**
* Defining Process dialog
**/
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Fetching Data....");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected JSONObject doInBackground(String... args) {
CommonFunctions commonFunctions = new CommonFunctions();
JSONObject json = commonFunctions.getQuesAns(category_id);
return json;
}
protected void onPostExecute(JSONObject json) {
/**
* Checks for success message.
**/
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
String red = json.getString(KEY_ERROR);
if (Integer.parseInt(res) == 1) {
pDialog.setTitle("Getting Data");
pDialog.setMessage("Loading Data...");
pDialog.dismiss();
JSONArray quest_ans = json.getJSONArray("quest_ans");
/* Clear all previous data in SQlite database.
**/
ParikshaDbHelper dbHelper = ParikshaDbHelper.getInstance(getActivity().getApplicationContext());
dbHelper.resetTables();
SQLiteDatabase db = dbHelper.getWritableDatabase();
if(quest_ans.length() > 0){
QuestAns questAns = new QuestAns();
for(int i=0; i<quest_ans.length(); i++){
JSONObject storeData = quest_ans.getJSONObject(i);
questAns.setId(storeData.getInt(ParikshaContract.QuestAns.COL_ID));
questAns.setCatId(storeData.getInt(ParikshaContract.QuestAns.COL_CAT_ID));
questAns.setQuestion(storeData.getString(ParikshaContract.QuestAns.COL_QUESTION));
questAns.setAnswer(storeData.getString(ParikshaContract.QuestAns.COL_ANSWER));
QuestAnsDao.insert(db, questAns);
}
}
List<QuestAns> questAns = QuestAnsDao.getAllByCategories(db, category_id);
if(questAns.size() > 0){
adapter = new CustomListViewArrayAdapter(getActivity()
.getApplicationContext(), R.layout.quesans_item,
questAns);
listView.setAdapter(adapter);
}
pDialog.dismiss();
} else if (Integer.parseInt(red) == 1) {
pDialog.dismiss();
}
} else {
pDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((HomeScreenActivity) activity).onSectionAttached(getArguments().getInt(
ARG_SECTION_NUMBER));
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("catId", category_id);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore last state for checked position.
category_id = savedInstanceState.getInt("catId");
}
}
}
我尝试了什么: -
请帮我跟踪问题并解决。
如果有任何打字或格式错误,我们深表歉意。