2012-02-28 16 views
1

一般的にJavaとOOPに関しては本当にnoobです。私はアプリのクラッシュに問題があります。主なアクティビティが煩雑で、全体のプログラムが適切に構成されていないためです。誰もが物事をスムーズに実行し、より良いアプリケーション構造を持つために次のコードをクリーンアップする方法について私にアドバイスできますか?私は物事を別のクラスに分けて、ほとんどの機能を別のクラスに入れておく必要があると思いますが、私は新しく本当に分かりません。私は電話(keyDispatchingTimedOutエラー)でアプリケーションを実行すると、ANRエラーを取得し続け、私の未組織のコードがこれを引き起こしていると思う。どんな助けも素晴らしいだろう!ありがとう。Androidをクリーンアップする主なアクティビティコード

package com.example.www; 

public class MainActivity extends Activity { 

    Button mCloseButton; 
    Button mOpenButton; 
    MultiDirectionSlidingDrawer mDrawer; 

    private Button send_button; 
    EditText msgTextField; 

    private LocationManager locManager; 
    private LocationListener locListener; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 
     setContentView(R.layout.main); 

     mDrawer.open(); 

     final SharedPreferences shared = getSharedPreferences("PEOPLE_PREFERENCES", MODE_PRIVATE); 
     final String phone = shared.getString("PHONE", ""); 

     String usr_id = shared.getString("USR_ID", null); 

     if(phone == null) { 
      TextView text = (TextView)findViewById(R.id.textView1); 
      text.setText("Please Enter Your Phone Number"); 

      AlertDialog.Builder alert = new AlertDialog.Builder(this); 

      alert.setTitle("Please Enter Your Phone Number"); 
      alert.setMessage("You must enter your phone number in order to use this application"); 

      final EditText input = new EditText(this); 
      alert.setView(input); 

      alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int whichButton) { 
       String value = input.getText().toString(); 
       if (value.length() == 10) { 
        Editor editor = shared.edit(); 
        editor.putString("PHONE", value); 
        editor.commit(); 
       } 
      } 
      }); 
      alert.show();  
     } 

     Button profile = (Button) findViewById(R.id.button1); 
     profile.setOnClickListener(new OnClickListener() { 

      public void onClick(View v) { 
       startActivity(new Intent(MainActivity.this, PreferencesActivity.class)); 
      } 
     }); 



     if (usr_id == null) { 

      char[] chars = "abcdefghijklmnopqrstuvwxyzABSDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray(); 
      Random r = new Random(System.currentTimeMillis()); 
      char[] id = new char[8]; 
      for (int i = 0; i < 8; i++) { 
       id[i] = chars[r.nextInt(chars.length)]; 
      } 
      usr_id = new String(id); 
      Editor editor = shared.edit(); 
      editor.putString("USR_ID", usr_id); 
      editor.commit(); 
     } 

     final String usr_id1 = shared.getString("USR_ID", "none"); 

     send_button = (Button)findViewById(R.id.button2); 

     send_button.setOnClickListener(new OnClickListener() { 
      private boolean running = false; 
      private CountDownTimer timer; 
      public void onClick(View v) { 
       if(!running) 
       { 
       running = true; 
       timer = new CountDownTimer(4000, 1000) { 

        @Override 
        public void onFinish() { 
         send_button.setText("GPS Sent"); 
         startLocation(); 
         sendId(usr_id1, phone); 
        } 

        @Override 
        public void onTick(long sec) { 
         send_button.setText("CANCEL (" + sec/1000 + ")"); 

        } 
       }.start(); 
       } 
       else 
       { 
       timer.cancel(); 
       send_button.setText("Send GPS"); 
       running = false; 
       } 
      } 
     }); 
    } 


    private void startLocation() 
    { 

     //get a reference to the LocationManager 
     locManager = 
      (LocationManager)getSystemService(Context.LOCATION_SERVICE); 

     //get the last known position 
     Location loc = 
      locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 

     //show the last known position 
     //showPosition(loc); 

     //checked to receive updates from the position 
     locListener = new LocationListener() { 
      public void onLocationChanged(Location location) { 
       showPosition(location); 
      } 
      public void onProviderDisabled(String provider){ 
       //labelState.setText("Provider OFF"); 
      } 
      public void onProviderEnabled(String provider){ 
       //labelState.setText("Provider ON "); 
      } 
      public void onStatusChanged(String provider, int status, Bundle extras){ 
       //Log.i("", "Provider Status: " + status); 
       //labelState.setText("Provider Status: " + status); 
      } 
     }; 

     locManager.requestLocationUpdates(
       LocationManager.GPS_PROVIDER, 0, 0, locListener); 
    } 

    private void showPosition(Location loc) { 
     if(loc != null) 
     { 

      Log.i("", String.valueOf(loc.getLatitude() + " - " + String.valueOf(loc.getLongitude()))); 

      send(loc); 
     } 

    } 

    private void send(Location loc) 
    { 
     String lat = String.valueOf(loc.getLatitude()); 
     String lon = String.valueOf(loc.getLongitude()); 

     SharedPreferences shared = getSharedPreferences("PEOPLE_PREFERENCES", MODE_PRIVATE); 
     final String usr_id2 = shared.getString("USR_ID", "none"); 

     if (lat != "0" && lon != "0") 
     { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://example.com/test/example1.php"); 
      //HttpPost httppost = new HttpPost("http://kblapdesk.com/myers27/receive.php"); 
     try { 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); //changed to 4 
      nameValuePairs.add(new BasicNameValuePair("lat", lat)); //changed "message" to "lat" changed "msg" to "lat" 
      nameValuePairs.add(new BasicNameValuePair("lon", lon)); //added this line 
      nameValuePairs.add(new BasicNameValuePair("id", usr_id2)); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      httpclient.execute(httppost); 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
     } 

     } 
     else 
     { 
      // display message if text fields are empty 
      Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show(); 
     } 

    } 

    private void sendId(String usr_id1, String phone) 
    { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://example.com/test/example.php"); 
      //HttpPost httppost = new HttpPost("http://kblapdesk.com/myers27/receive_user.php"); 
     try { 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); //changed to 4 

      nameValuePairs.add(new BasicNameValuePair("id", usr_id1)); 

      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      httpclient.execute(httppost); 
      //msgTextField.setText(""); // clear text box 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
     } 

     mCloseButton.setOnClickListener(new OnClickListener() { 
      public void onClick(View v) 
      { 
       mDrawer.animateClose(); 
      } 
     }); 

     mOpenButton.setOnClickListener(new OnClickListener() { 

      public void onClick(View v) 
      { 
       if(!mDrawer.isOpened()) 
        mDrawer.animateOpen(); 
      } 
     }); 
    } 

    @Override 
    public void onContentChanged() 
    { 
    super.onContentChanged(); 
    mCloseButton = (Button) findViewById(R.id.button_open); 
    mOpenButton = (Button) findViewById(R.id.button_open); 
    mDrawer = (MultiDirectionSlidingDrawer) findViewById(R.id.drawer); 
    } 
} 

答えて

0

私はLocationListenerをまったく異なるクラスにカプセル化します。それはあなたのコードの大部分を短縮し、扱うことができるチャンクを残すべきです。

また、あなたのMainActivityには、いくつかのHTTP投稿メソッドまたはWebリクエストメソッドがあるようです。それらを取り出して別のクラスに入れてください。それにはActivityServerのような名前を付けてください。

ActivityServerクラスでは、Web要求を実行するときにUIスレッドをブロックしないように、コールバックおよび非同期インターフェイスを作成する必要があります。

+0

[OK]をクリックして、主なアクティビティからどのように呼び出すことができますか? – mkyong

+0

Webサーバーの場合は、インスタンス化してMyServer.send(params)を呼び出します。 LocationListenerの場合、必要なパラメータを渡す必要があるため、適切なメソッドを独自に呼び出すことができます。 – hwrdprkns

+0

これが私がANRエラーを取得している理由だと思いますか? – mkyong

関連する問題