0

나는 Actionbar Sherlock을 사용하는 앱에 3 개의 탭과 각각의 조각이 들어 있습니다. 앱에 로그인하면 Book Buy 파편이 기본적으로 실행됩니다. 내가 알아 차린 것은 로그인이 실행 된 후에 Sell 부분이 부분적으로 실행된다는 것입니다. 다음과 같은 흐름이 있습니다. 로그인 -> Frag -> Frag -> Json Parser -> Frag 판매 -> Json Parser -> Book Buy -> Custom Adapter.Android Fragment 호출하지 않고 실행

정확한 흐름은 Login -> Book Buy Frag -> Json Parser -> Book Buy -> Custom Adapter입니다.

로그인에서 첫 화면으로 이동하는 데 시간이 걸리는 것은 당연합니다. 아무도이 이상한 행동으로 나를 도울 수 있습니까? 이 시점에서 탭을 선택하지 않았다는 사실을 명심하십시오.

로그인 자바 :

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(); 
} 

} 

도서 구입 파편 :

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"); 
        } 

       }); 

      } 
     }); 
    } 
} 

판매의 파편은 :

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

실행 바 셜록은 때로는 탭이 왼쪽로드에서 현재의 권리 탭을 빠르게 변경할 수 있습니다. 다른 프로젝트에서이 문제가 발생했습니다 : onCreate에 코드를 두지 않으려 고합니다. 실행하지 않으려 고합니다.