Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/180.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 清理Android主活动代码_Java_Android_Oop_Main Activity - Fatal编程技术网

Java 清理Android主活动代码

Java 清理Android主活动代码,java,android,oop,main-activity,Java,Android,Oop,Main Activity,在Java和OOP方面,我是一个真正的noob。我的应用程序崩溃了,我想这是因为我的主要活动杂乱无章,我的整个程序结构不正确。有谁能建议我如何清理下面的代码,使事情运行更顺畅,并有一个更好的应用程序结构?我认为我需要将事物划分为不同的类,并将大部分函数保留在不同的类中,但我是新的,并且确实不确定。当我在手机上运行应用程序时,我不断收到一个ANR错误(keyDispatchingTimedOut错误),我认为是我的无组织代码导致了这一错误。任何帮助都会很好!谢谢 package com.e

在Java和OOP方面,我是一个真正的noob。我的应用程序崩溃了,我想这是因为我的主要活动杂乱无章,我的整个程序结构不正确。有谁能建议我如何清理下面的代码,使事情运行更顺畅,并有一个更好的应用程序结构?我认为我需要将事物划分为不同的类,并将大部分函数保留在不同的类中,但我是新的,并且确实不确定。当我在手机上运行应用程序时,我不断收到一个ANR错误(keyDispatchingTimedOut错误),我认为是我的无组织代码导致了这一错误。任何帮助都会很好!谢谢

    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 );
   }
}
package.com.example.www;
公共类MainActivity扩展了活动{
按钮mclose按钮;
按钮MOPENBUTON;
多向滑轨抽屉;
私人按钮发送按钮;
编辑文本msgTextField;
私人场所经理;
私有位置侦听器;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE\u NO\u TITLE);
setContentView(R.layout.main);
mDrawer.open();
最终SharedReferences shared=GetSharedReferences(“人员偏好”,模式为私有);
final String phone=shared.getString(“phone”,“phone”);
字符串usr\u id=shared.getString(“usr\u id”,null);
如果(电话==null){
TextView text=(TextView)findViewById(R.id.textView1);
text.setText(“请输入您的电话号码”);
AlertDialog.Builder alert=新建AlertDialog.Builder(此);
alert.setTitle(“请输入您的电话号码”);
alert.setMessage(“您必须输入您的电话号码才能使用此应用程序”);
最终编辑文本输入=新编辑文本(本);
alert.setView(输入);
alert.setPositiveButton(“确定”,新的DialogInterface.OnClickListener(){
public void onClick(对话框接口对话框,int whichButton){
字符串值=input.getText().toString();
if(value.length()==10){
Editor=shared.edit();
编辑器.putString(“电话”,值);
commit();
}
}
});
alert.show();
}
按钮配置文件=(按钮)findViewById(R.id.button1);
setOnClickListener(新的OnClickListener(){
公共void onClick(视图v){
startActivity(新意图(MainActivity.this、PreferencesActivity.class));
}
});
如果(usr_id==null){
char[]chars=“abcdefghijklmnopqrstuvxyzabdefghjklmnopqrstuvxyz1234567890”。toCharArray();
Random r=新的Random(System.currentTimeMillis());
char[]id=新字符[8];
对于(int i=0;i<8;i++){
id[i]=字符[r.nextInt(字符长度)];
}
usr_id=新字符串(id);
Editor=shared.edit();
putString(“USR\u ID”,USR\u ID);
commit();
}
最终字符串usr_ID 1=shared.getString(“usr_ID”,“none”);
发送按钮=(按钮)findViewById(R.id.button2);
send_button.setOnClickListener(新的OnClickListener(){
私有布尔运行=false;
私人倒计时;
公共void onClick(视图v){
如果(!正在运行)
{
运行=真;
计时器=新的倒计时计时器(40001000){
@凌驾
公共无效onFinish(){
发送按钮。设置文本(“GPS发送”);
惊吓定位();
sendId(usr_id1,电话);
}
@凌驾
公共void onTick(长秒){
send_button.setText(“取消(“+sec/1000+”));
}
}.start();
}
其他的
{
timer.cancel();
send_button.setText(“发送GPS”);
运行=错误;
}
}
});
}  
私人空间
{
//获取LocationManager的引用
本地经理=
(LocationManager)getSystemService(Context.LOCATION\u服务);
//获取最后一个已知位置
位置loc=
LocationManager.getLastKnownLocation(LocationManager.GPS\U提供程序);
//显示最后一个已知位置
//展示位置(loc);
//选中以接收来自该职位的更新
locListener=新的LocationListener(){
已更改位置上的公共无效(位置){
展示位置(位置);
}
公共无效onProviderDisabled(字符串提供程序){
//labelState.setText(“提供程序关闭”);
}
公共无效onProviderEnabled(字符串提供程序){
//labelState.setText(“提供程序打开”);
}
public void onStatusChanged(字符串提供程序、int状态、Bundle extra){
//Log.i(“,”提供者状态:“+状态);
//labelState.setText(“提供者状态:+状态”);
}
};
LocalManager.RequestLocationUpdate(
LocationManager.GPS_提供程序,0,0,LocalListener);
}
私人空位展示位置(位置loc){
如果(loc!=null)
{
Log.i(“”,String.valueOf(loc.getLatitude()+“-”+String.valueOf(loc.getLatitude()));
发送(loc);
}
}
专用无效发送(位置loc)
{
String lat=String.valueOf(loc.getLatitude());
String lon=String.valueOf(loc.getLongitude());
SharedPreferences shared=getSharedPreferences(“个人偏好”,