2012-02-28 9 views
0

私はJavaとAndroidにはいくらか新しく、クラスやアクティビティに問題があります。コードを整理してMainActivityから別のクラスに移動しましたが、クラスの代わりに新しいアクティビティを作成するだけでアプリを稼働させることができました。私がメインビューに滞在し、ちょうど主な活動のボタンから アクティビティをクラスに変更する - Android

  • クラスのメソッドを使用する必要が

    • 、カウントダウンした後、LocationActivityを呼び出します。
    • LocationActivityはGPS座標を見つけて、それらをSendActivityに送信します。

    これは、私がちょうどlocationListenerを起動する必要があったので、これを動作させる唯一の方法です。したがって、onCreateセクションで開始しました。

    MainActivity.java

    public class MainActivity extends Activity { 
    
        Button mCloseButton; 
        Button mOpenButton; 
        MultiDirectionSlidingDrawer mDrawer; 
    
        private Button send_button; 
        Button sendButton; 
        EditText msgTextField; 
    
        @Override 
        public void onCreate(Bundle savedInstanceState) { 
         super.onCreate(savedInstanceState); 
         requestWindowFeature(Window.FEATURE_NO_TITLE); 
         setContentView(R.layout.main); 
    
         send_button = (Button)findViewById(R.id.button2); 
    
         mDrawer.open(); 
    
         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(); 
          } 
         }); 
    
         final SharedPreferences shared = getSharedPreferences("PEOPLE_PREFERENCES", MODE_PRIVATE); 
         final String first = shared.getString("FIRSTNAME", ""); 
         final String last = shared.getString("LASTNAME", "0"); 
    
    
         ///////Profile Button//////////////// 
         Button profile = (Button) findViewById(R.id.button1); 
         profile.setOnClickListener(new OnClickListener() { 
    
          public void onClick(View v) { 
           startActivity(new Intent(MainActivity.this, PreferencesActivity.class)); 
          } 
         }); 
         /////////////////////////////////// 
    
         //////Generate ID////////////////// 
         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(); 
         } 
         //////////////////////////////////     
    
         ////////Send Alert//////////////// 
         ///////Begin Timer/////////////// 
         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("SENT"); 
             startActivity(new Intent(MainActivity.this, LocationActivity.class)); 
             SendUserActivity.sendId(usr_id1, first, last);           
            } 
    
            @Override 
            public void onTick(long sec) { 
             send_button.setText("CANCEL (" + sec/1000 + ")"); 
    
            } 
           }.start(); 
           } 
           else 
           { 
           timer.cancel(); 
           send_button.setText("Send!"); 
           running = false; 
           } 
          } 
         }); 
        } 
        /////////////////////////////////// 
    
    
        @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); 
        } 
    } 
    

    LocationActivity.java

    package com.alex.www; 
    
    import android.app.Activity; 
    import android.content.Context; 
    import android.content.SharedPreferences; 
    import android.location.Location; 
    import android.location.LocationListener; 
    import android.location.LocationManager; 
    import android.os.Bundle; 
    import android.util.Log; 
    import android.widget.Button; 
    
    public class LocationActivity extends Activity { 
    
    
        private LocationManager locManager; 
        private LocationListener locListener; 
    
    
        public void onCreate(Bundle savedInstanceState) { 
         super.onCreate(savedInstanceState); 
         startLocation(); 
        } 
    
        void startLocation() 
        { 
    
         SharedPreferences shared = getSharedPreferences("PEOPLE_PREFERENCES", MODE_PRIVATE); 
        final String usr_id2 = shared.getString("USR_ID", "none"); 
    
        //get a reference to the LocationManager 
        locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    
    
        //checked to receive updates from the position 
        locListener = new LocationListener() { 
         public void onLocationChanged(Location location) { 
          SendActivity.send(location, usr_id2); 
         } 
         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); 
          } 
         }; 
    
         locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener); 
        } 
    } 
    

    SendActivity.java

    package com.alex.www; 
    
    import java.io.IOException; 
    import java.util.ArrayList; 
    import java.util.List; 
    
    import org.apache.http.NameValuePair; 
    import org.apache.http.client.ClientProtocolException; 
    import org.apache.http.client.HttpClient; 
    import org.apache.http.client.entity.UrlEncodedFormEntity; 
    import org.apache.http.client.methods.HttpPost; 
    import org.apache.http.impl.client.DefaultHttpClient; 
    import org.apache.http.message.BasicNameValuePair; 
    
    import android.app.Activity; 
    import android.content.SharedPreferences; 
    import android.location.Location; 
    import android.os.Bundle; 
    import android.util.Log; 
    import android.widget.Button; 
    import android.widget.EditText; 
    import android.widget.TextView; 
    
    public class SendActivity extends Activity { 
    
        public void onCreate(Bundle savedInstanceState) { 
         super.onCreate(savedInstanceState); 
        } 
    
        public static void send(Location loc, String usr_id2) 
        { 
    
         Log.i("", String.valueOf(loc.getLatitude() + " - " + String.valueOf(loc.getLongitude()))); 
    
         String lat = String.valueOf(loc.getLatitude()); 
         String lon = String.valueOf(loc.getLongitude()); 
    
         HttpClient httpclient = new DefaultHttpClient(); 
         HttpPost httppost = new HttpPost("http://example.com/test/example.php"); 
    
         try { 
          List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
          nameValuePairs.add(new BasicNameValuePair("lat", lat)); 
          nameValuePairs.add(new BasicNameValuePair("lon", lon)); 
          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 
         } 
        } 
    
    } 
    
  • +0

    すべての点を尊重して、Androidを同時に学習する負担なしにJavaを学びましょう。私はあなたがそのアドバイスを感謝しないだろうと確信していますが、Javaをしっかり理解すれば、それがあなたにとって最良の行動コースであると理解できます。 – mah

    答えて

    0

    質問が面白かったので、私は、より明確にするため、あなたの投稿を編集しました。これは多くの新しい開発者がAndroidで始めるときに持つジレンマです。そして、私を信じて、本当に悪いコードを見ました。適切なアドバイスを適切なタイミングで入手することが重要です。だからここに行く。

    あなたは正しい方向にあります。すべてのビューには独自のアクティビティが必要です。その習慣から抜け出してはいけません。あなたはJavaの方法を行っている場合、あなたは活動のを使用しないように誘惑されますが、それはあなたに非常に悪いアンドロイドの開発者になります。

    はい、Androidアプリを書く方法についてもう少し詳しくお読みください。

    1ビュー1の活動原則を使用すると、アンドロイドOSによって多くのサポートが提供されます。たとえば、順番に戻るボタンがサポートされます。

    +0

    フラグメントには何が起こりますか? – Bostone

    +0

    あなたの質問を理解できませんでしたか? –

    0

    一般的なアプローチは、次のようになります。

    それらのクラスは(アクティビティを拡張削除)と、パラメータとしてコンテキストを受け入れる両方のクラスのためのcontructorsを作ることを確認します。メソッドを準備し、主なアクティビティでクラスの新しいインスタンスを作成して、メソッドを使用できるようにします。多分あなたはいくつかのものを適応させる必要がありますが、それは大きな問題ではありません。

    ところで:それは推奨されている全ての長いオペレーション(位置更新のように、HTTP /レシーブを送る)

    +0

    私のコードの例を教えてもらえますか?ちょうど私を始めさせる何か。 LocationActivityからextendsアクティビティ部分を削除すると、 'getSystemService'はエラーを投げて、そのメソッドを作成するように求めます。 – mkyong

    0

    活動がクラス..ですあなたのUIが凍結ではないので、threads/background operationを使用して管理し、ANR力閉鎖を回避しています。外部サービスを使用する操作を行う必要がある場合や、潜在的に長いものを実行する必要がある場合は、AsyncTaskを使用して、それ自体のスレッドで行うほうがずっと良いと言われています。 refer to this article詳細については

    関連する問題