如何使我的代码(AsyncTask)更干净?

时间:2016-01-10 03:24:48

标签: java android android-asynctask

我需要为我的最后一年项目构建一个Android应用程序,(我是Android开发新手)。有没有想法最小化代码或可能分成不同的类。

我想让我的主要活动更短,更清洁维护,最好是使用MVC架构进行编码。稍后会添加更多UI组件。 谢谢你的关注。

public class MainActivity extends AppCompatActivity {
    Button find_button;
    EditText user_origin;
    EditText user_destination;
    private TextView json_output;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        find_button = (Button)findViewById(R.id.find_button);
        json_output = (TextView)findViewById(R.id.json_output);
        user_origin = (EditText)findViewById(R.id.user_origin);
        user_destination = (EditText)findViewById(R.id.user_destination);

        find_button.setOnClickListener(new View.OnClickListener(){
            String origin;
            String new_origin;
            String destination;
            String new_user_destination;

            @Override
            public void onClick(View v){
               origin = user_origin.getText().toString();
               new_origin = origin.replaceAll(" ", "+");
               destination = user_destination.getText().toString();
               new_user_destination = destination.replaceAll(" ", "+");

               String link = "https://maps.googleapis.com/maps/api/directions/json?origin=" + new_origin + "&destination=" + new_user_destination + "&mode=transit&key=AIzaSyD83XCiGtJyo6Ln8c7yyyrQwmFDFZB_oiU";

                //json_output.setText(link);
                new JSONTask().execute(link);
            }
        });



    }

    public class JSONTask extends AsyncTask<String,String,String> {

        @Override
        protected String doInBackground(String... params){
            HttpURLConnection connection = null;
            BufferedReader reader = null;

            try{
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                InputStream stream = connection.getInputStream();

                reader = new BufferedReader(new InputStreamReader(stream));

                StringBuffer buffer = new StringBuffer();

                String line = "";
                while((line = reader.readLine()) != null ){
                    buffer.append(line);
                }

                String final_json = buffer.toString();

                return buffer.toString();

            } catch (MalformedURLException e){
                e.printStackTrace();
            } catch (IOException e){
                e.printStackTrace();
            } finally {
                if(connection != null) {
                    connection.disconnect();
                }
                try {
                    if(reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result){
            super.onPostExecute(result);
            json_output.setText("result:" +result);
        }
    }
}

2 个答案:

答案 0 :(得分:0)

你可以把你的JSONTask分开作为一个简单的类,并执行它的任务,然后在这个类中定义一个接口来传递一些消息或数据应该由其他类处理,并添加一个参数类型就是这个接口对于构造函数并将其保存为field.like:

public class JSONTask extends AsyncTask<String,String,String>{
    private OnHandleResult mResult;
    private String[] mParams;
    public JSONTask(OnHandleResult onHandleResult,String... params){
        this.mResult = onHandleResult;
        this.mParams = params;
    }

    protected String doInBackground(String... params){
    //params is empty,get params from this.mParams
    }

     @Override
    protected void onPostExecute(String result){
        super.onPostExecute(result);
        //json_output.setText("result:" +result);
        this.mResult.handleResult(result);
    }

    public static interface OnHandleResult{
        void handleResult(final String result);
    }
}

然后让你的活动实现接口onHandleResult,并且hanlde结果:将text设置为textview:

public class MainActivity extends AppCompatActivity implements JSONTask.OnHandleResult{
    void handleResult(final String result){
         json_output.setText("result:" +result);
    }
}

并执行如下任务:

new JSONTask(this,link).execute();

答案 1 :(得分:0)

通常,每个文件有1个类是个好习惯。 您可以使MainActivity更具可读性

public class MainActivity extends AppCompatActivity {

Button find_button;
EditText user_origin;
EditText user_destination;
private TextView json_output;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    find_button = (Button) findViewById(R.id.find_button);
    json_output = (TextView) findViewById(R.id.json_output);
    user_origin = (EditText) findViewById(R.id.user_origin);
    user_destination = (EditText) findViewById(R.id.user_destination);

    String link = build_link(user_origin, user_destination);

    MyListener l = new MyListener(link);
    find_button.setOnClickListener(l);
}

private String build_link(EditText user_origin, EditText user_destination) {

    String origin = user_origin.getText().toString();
    String new_origin = origin.replaceAll(" ", "+");
    String destination = user_destination.getText().toString();
    String new_user_destination = destination.replaceAll(" ", "+");

    return "https://maps.googleapis.com/maps/api/directions/json?origin=" + new_origin + "&destination=" + new_user_destination + "&mode=transit&key=AIzaSyD83XCiGtJyo6Ln8c7yyyrQwmFDFZB_oiU";
}

通过隔离听众的实施:

public class MyListener implements View.OnClickListener {

String link;

public MyListener(String link) {

    this.link = link;
}

@Override
public void onClick(View v) {

    new JSONTask().execute(link);
}