我有一个使用Actionbar Sherlock的应用程序,其中包含3个标签及其各自的片段。当我登录应用程序时,默认情况下应该执行Book Buy片段。我注意到在执行Login之后,部分执行了Sell片段。 这是它正在做的流程:登录 - >卖Frag - >购买Frag - > Json Parser - >卖Frag - > Json Parser - >书籍购买 - >定制适配器。
正确的流程应该是:登录 - >购买Frag - > Json Parser - >书籍购买 - >自定义适配器。
毋庸置疑,从登录到第一个屏幕需要一段时间。任何人都可以帮我解决这个奇怪的行为吗请记住,此时尚未选择任何标签。
登录Java:
public class LoginActivity extends Activity {
//TextView text;
ProgressDialog pDialog;
String uEmailLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_scrn);
System.out.println("LoginActivity starte befoe session");
//Declared the two variables as "final" for ICS compiler to recognize them in onClickListener
final EditText userEmail = (EditText) findViewById(R.id.emailInpt);
final EditText userPass = (EditText) findViewById(R.id.passwordInpt);
final TextView text = (TextView) findViewById(R.id.logError);
Button loginBtn = (Button) findViewById(R.id.loginBtn);
Button registerBtn = (Button) findViewById(R.id.registerBtn);
//Executes this code when the submit button is pressed
loginBtn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if(userEmail.getText().length()== 0) {
text.setText("Enter Email Address");
}
else if(userPass.getText().length()== 0) {
text.setText("Enter Password");
}
else {
System.out.println("LogAct Check 2");
//Start Async task here for Http...because 4.0 can't process data on main UI
new CheckLogin().execute(userEmail.getText().toString(),
userPass.getText().toString());
//Clears input data off phone screen after login button is hit
userEmail.setText("");
userPass.setText("");
//finish();
}
}
});
//original end of onClickListner
//});
// Link to Register Screen
registerBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent register = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(register);
finish();
}
});
}
//Class to check for successful Login
private class CheckLogin extends AsyncTask<String, String, String> {
//Progress Dialog
//private ProgressDialog pDialog;
//Show Progress Dialog before starting background thread
@Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("LogAct onPreExecute started");
pDialog = new ProgressDialog(LoginActivity.this); //might can only be activity
//pDialog = new ProgressDialog(getActivity());//might can only be activity
pDialog.setMessage("Logging in...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
//System.out.println("onPreExecute finished");
}
//Get Login Info
protected String doInBackground(String... arg0) {
JSONObject json_data = null;
String result = null;
InputStream is = null;
StringBuilder sb = null;
//InputStream is = null;
//Opens internet connection and prepares the files to be used in processing
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/bkbarter.php"); //emulator
try{
//Loads the Array with the values to be sent to php code for db processing
ArrayList <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("userAction", "login"));
nvps.add(new BasicNameValuePair("userEmail", arg0[0]));
nvps.add(new BasicNameValuePair("userPass", arg0[1]));
//Stores the user email to be later stored as a global variable in AsyncTask
uEmailLogin = arg0[0];
httppost.setEntity(new UrlEncodedFormEntity(nvps));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
//Shows logcat status response to determine if data was sent correctly
//System.out.println("output = " + response);
Log.i("onClickListner", response.getStatusLine().toString());
//Clears input data off phone screen after login button is hit
} catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//Converts the variables retrieved into a string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while((line = reader.readLine()) != null) {
sb.append(line + "\n");
//System.out.println(sb);
}
is.close();
result = sb.toString();
System.out.println(result);
} catch(Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
return result;
}
//After completing background task, dismiss the progress dialog
@Override
protected void onPostExecute(final String result) { // might need to be (String result) here
//super.onPostExecute(result);
//JSONObject json_data = null;
//dismiss the dialog after getting all the records
if(pDialog != null) {
pDialog.dismiss();
}
LoginActivity.this.runOnUiThread(new Runnable() {
public void run() {
JSONObject json_data = null;
String success_resp_code = null;
String error_resp_code = null;
String userAction = null;
//Parses the string to a JSON object
try {
json_data = new JSONObject(result);
//Stores the json response code
success_resp_code = json_data.getString("success");
error_resp_code = json_data.getString("error");
userAction = json_data.getString("userAction");
} catch (JSONException e) {
Log.e("Login/JSON Parser", "Error parsing data " + e.toString());
}
//Checks login status to for success or failure
try {
//if (json_data.getString("success") != null) {
if (success_resp_code != null) {
if(Integer.parseInt(success_resp_code) == 1){
// user successfully logged in
Toast.makeText(getApplicationContext(), "You have successfully logged in", Toast.LENGTH_SHORT).show();
//Calls Globals to set user Email as global variable
((Globals) getApplicationContext()).setEmailLogin(uEmailLogin);
//Start BookBarter Activity
Intent bookBarter = new Intent(getApplicationContext(), BookBarterActivity.class);
startActivity(bookBarter);
//Close Login screen
// finish();
}else if (json_data.getString("error") != null) {
if(Integer.parseInt(error_resp_code) == 1) {
//User entered incorrect password
Toast.makeText(getApplicationContext(), "Incorrect Password", Toast.LENGTH_SHORT).show();
}else if(Integer.parseInt(error_resp_code) == 2) {
//User does not exist
Toast.makeText(getApplicationContext(), "User does not exist", Toast.LENGTH_SHORT).show();
}
}
}
} catch(Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
System.out.println("LogAct onPostExecute finished");
}
});
}
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if(pDialog != null)
pDialog.dismiss();
pDialog = null;
finish();
}
}
购买Frag:
public class BuyFragTab extends SherlockListFragment {
//Progress Dialog
private ProgressDialog pDialog;
//Creating JSON Parser Object
JSONParser jsonParser = new JSONParser();
//bookBuy JSON array
JSONArray bookBuyInfo = null;
//Array of book information
ArrayList<Bookinfo> bookArray = new ArrayList<Bookinfo>();
//Book ListView
ListView bookLV;
MyCustomAdapter adapter;
//Search EditText
EditText titleSearch;
//DualPane variable
boolean mDualPane;
int mCurCheckPosition = 0;
//Holder array for json data movement
public static ArrayList<String> bkRecs;
Context context;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.buy_tbfrag, container, false);
bookLV = (ListView)view.findViewById(android.R.id.list);
//enables filtering for the contents of the given ListView bookLV
bookLV.setTextFilterEnabled(true);
//Search inputed book title
titleSearch = (EditText)view.findViewById(R.id.titleSearch);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState){
//super.onActivityCreated(savedInstanceState);
//System.out.println("onActivityCreated executed");
bookArray = new ArrayList<Bookinfo>();
//Load bookArray in Background Thread
new LoadBookBuyInfo().execute();
View detailsFragment = getActivity().findViewById(R.id.details_fragment_container);
mDualPane = detailsFragment != null
&& detailsFragment.getVisibility() == View.VISIBLE;
//Set up click listener for the item clicked in the ListView
bookLV.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id){
String selectTitle, selectAuthor, selectIsbn, selectCond, selectPrice = null;
String selectSeller, selectEmail, selectPhone, selectCollege = null;
//When item is clicked, show it's detailed view
Bookinfo bkRecs = (Bookinfo)parent.getItemAtPosition(position);
//Loads the Book Detail Information
selectTitle = bkRecs.getTitle();
...loads data...
System.out.println(" Title = " + selectTitle + " Author = " + selectAuthor);
//If in Dual Pane/Landscape mode, send selected user information to Show Details to display
//to the screen
if (mDualPane) {
showDetails(selectTitle, selectAuthor, selectIsbn, selectCond, selectPrice,
selectSeller, selectEmail, selectPhone, selectCollege);
}else {
//If in Portrait mode, create an intent object to start BookDetailsActivity
Intent bkIntent = new Intent("com.skipster.BookBarter.BOOKDETAILSACTIVITY");
//Setting data (the clicked item's position to the intent
bkIntent.putExtra("Selected_Title", selectTitle);
...put Extra data...
//Start the activity
startActivity(bkIntent);
}
}
});
super.onActivityCreated(savedInstanceState);
}
//manages screen orientation flips********************************//
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
//Landscap Mode screen processing
void showDetails(String Title, String Author, String Isbn, String Cond, String Price, String Seller,
String Email, String Phone, String College){
//instantiating the fragment BookDetailsFragment
SherlockFragment detailsFragment = new BookDetailsFragment();
//get fragment manager for fragment related operations
FragmentManager fm = getFragmentManager();
//get fragment transaction object, which can add, move or replace a fragment
FragmentTransaction ft = fm.beginTransaction();
//creating a bundle object to pass the data (clicked item's position)
//from this activity to fragment
Bundle b = new Bundle();
//loading bundle object
b.putString("Selected_Title", Title);
...
//setting/sending the bundle object to the fragment
//edited object is received and sent to be displayed
detailsFragment.setArguments(b);
System.out.println("Show Details check2");
ft.replace(R.id.details_fragment_container, detailsFragment);
System.out.println("Show Details check3");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
//Allows for user to press back button to go back in reverse order
//Works properly in landscape mode but not in portrait
ft.addToBackStack(null);
//Executing the transaction
ft.commit();
return;
}
//Background AsyncTask to load all BookBuyInfo by making Http Request
class LoadBookBuyInfo extends AsyncTask<String, String, String> {
//Show Progress Dialog before starting background thread
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());//might can only be activity
pDialog.setMessage("Loading Books...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
//Get BookBuyInfo Data
protected String doInBackground(String... arg0) {
//Building parameters
ArrayList<NameValuePair> bookValues = new ArrayList<NameValuePair>();
System.out.println("doInBackground executed");
//Loads user action to retrieve the book records
bookValues.add(new BasicNameValuePair("userAction", "GETR"));
//getting JSON string from URL, "GETR" = get entire record
JSONObject json = jsonParser.makeHttpRequest("http://10.0.2.2/bkbarter.php", "GETR", bookValues);
//Check logcat for JSON response
Log.d("Book Buy JSON: ", json.toString());
//Get JSON Data
try {
bookBuyInfo = json.getJSONArray("books");
//loop through all books and load data
for (int i = 0; i < bookBuyInfo.length(); i++) {
JSONObject b = bookBuyInfo.getJSONObject(i);
String seller = b.getString("Name");
...book info...
//creating new book record for bookArray
Bookinfo bkRecs = new Bookinfo(title, author, isbn, cond, price,
seller, email, phone, college);
//Add record to arrayList
bookArray.add(bkRecs);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
//After completing background task, dismiss the progress dialog
protected void onPostExecute(String file_url) { // might need to be (String result) here
//dismiss the dialog after getting all the records
//pDialog.dismiss();
if(pDialog != null) {
pDialog.dismiss();
}
//update UI from background thread
//runOnUiThread(new Runnable() {
getActivity().runOnUiThread(new Runnable() {
public void run() {
//updating parsed JSON data into ListView
adapter = new MyCustomAdapter(getActivity(), R.layout.buy_tbfrag, bookArray);
bookLV.setAdapter(adapter);
//Enable Search filter to search titles as each letter is inputed
titleSearch.addTextChangedListener(new TextWatcher(){
@Override
public void afterTextChanged(Editable cs){
//TODO Auto generated method-stub
}
@Override
public void beforeTextChanged(CharSequence cs, int start, int count, int after){
//TODO Auto generated method-stub
}
@Override
public void onTextChanged(CharSequence cs, int start, int before, int count){
//When user changed the text
adapter.getFilter().filter(cs.toString());
System.out.println("onTextChanged executed");
}
});
}
});
}
}
出售Frag:
public class SellFragTab extends SherlockFragment {
EditText sbkTitle, sbkAuthor, sbkISBN, sbkCond, sbkPhone, sbkPrice, sbkCollege;
TextView text;
//Progress Dialog
private ProgressDialog pDialog;
//bookBuy JSON array
JSONArray bookBuyInfo = null;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
System.out.println("Sell Frag Tab executed");
View view = inflater.inflate(R.layout.sell_tbfrag, container, false);
sbkTitle = (EditText)view.findViewById(R.id.sbookTitle);
sbkAuthor = (EditText)view.findViewById(R.id.sbookAuthor);
sbkISBN = (EditText)view.findViewById(R.id.sbookISBN);
sbkCond = (EditText)view.findViewById(R.id.sbookCond);
sbkPhone = (EditText)view.findViewById(R.id.sbookPhone);
sbkPrice = (EditText)view.findViewById(R.id.sbookPrice);
sbkCollege = (EditText)view.findViewById(R.id.sbookCollege);
text = (TextView)view.findViewById(R.id.regError);
Button subButn = (Button)view.findViewById(R.id.subButn);
System.out.println("Sell Frag Tab Check 2");
subButn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
if (sbkTitle.getText().length() == 0) {
text.setText("Enter Book Title");
}
else if (sbkAuthor.getText().length() == 0) {
text.setText("Enter Book Author");
}
else if (sbkCond.getText().length() == 0) {
text.setText("Enter Book Condition");
}
else if (sbkPhone.getText().length() == 0) {
text.setText("Enter Phone Number");
}
else if (sbkCollege.getText().length() == 0) {
text.setText("Enter College Name");
}
else if (sbkPrice.getText().length() == 0) {
text.setText("Enter Book Price");
}
else {
//Gets the global uEmailLogin for comparison in the db. This will allow the db to
//be updated with book info if all they previously did was register.
String uEmailLogin = ((Globals) getActivity().getApplication()).getEmailLogin();
//Start Async task here for Http...because 4.0 can't process data on main UI
new PostBookInfo().execute(sbkTitle.getText().toString(), sbkAuthor.getText().toString(),
sbkISBN.getText().toString(), sbkCond.getText().toString(),
sbkPhone.getText().toString(), sbkCollege.getText().toString(),
sbkPrice.getText().toString(), uEmailLogin);
//Clears input data off phone screen after login button is hit
sbkTitle.setText("");
sbkAuthor.setText("");
sbkISBN.setText("");
sbkCond.setText("");
sbkPhone.setText("");
sbkCollege.setText("");
sbkPrice.setText("");
//finish();
}
}
});
return view;
}
//Background AsyncTask to load all BookBuyInfo by making Http Request
class PostBookInfo extends AsyncTask<String, String, String> {
//Show Progress Dialog before starting background thread
//@Override
//protected void onPreExecute() {
// super.onPreExecute();
// pDialog = new ProgressDialog(getActivity());//might can only be activity
// pDialog.setMessage("Selling...");
// pDialog.setIndeterminate(false);
// pDialog.setCancelable(false);
// pDialog.show();
//}
//Get BookBuyInfo Data
protected String doInBackground(String... arg0) {
JSONObject json_data = null;
String result = null;
InputStream is = null;
StringBuilder sb = null;
//InputStream is = null;
//Opens internet connection and prepares the files to be used in processing
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/bkbarter.php");
try{
//Loads the Array with the values to be sent to php code for db processing
ArrayList <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("userAction", "postr"));
...load data...
System.out.println("nvps = " + nvps);
httppost.setEntity(new UrlEncodedFormEntity(nvps));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
//Shows logcat status response to determine if data was sent correctly
Log.i("onClickListner", response.getStatusLine().toString());
} catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//Converts the variables retrieved into a string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while((line = reader.readLine()) != null) {
sb.append(line + "\n");
System.out.println(sb);
}
is.close();
result = sb.toString();
} catch(Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
return(result);
}
//After completing background task, dismiss the progress dialog
@Override
protected void onPostExecute(final String result) { // might need to be (String result) here
getActivity().runOnUiThread(new Runnable() {
public void run() {
JSONObject json_data = null;
String success_resp_code = null;
String error_resp_code = null;
String userAction = null;
//Parses the string to a JSON object
try {
json_data = new JSONObject(result);
success_resp_code = json_data.getString("success");
error_resp_code = json_data.getString("error");
userAction = json_data.getString("userAction");
} catch (JSONException e) {
Log.e("Register/JSON Parser", "Error parsing data " + e.toString());
}
//Checks register status to for success or failure
try {
if (json_data.getString("success") != null &&
Integer.parseInt(success_resp_code) == 1){
//Successful save of book information
Toast.makeText(getActivity().getApplicationContext(), "Book info has been saved",
Toast.LENGTH_SHORT).show();
}else if(json_data.getString("error") != null &&
Integer.parseInt(error_resp_code) == 1) {
//Unsuccessful saving book information
Toast.makeText(getActivity().getApplicationContext(), "Error saving book info",
Toast.LENGTH_SHORT).show();
}
} catch(Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
}
});
}
}
}
答案 0 :(得分:0)
Actionbar Sherlock有时也会加载当前标签的左右两个标签,以便快速更改标签。我在另一个项目中遇到了这个问题:尝试在onCreate中省略你不想执行的代码。