在 Android 中拆分过大的方法

splitting a too large method in android

提问人:imacro 提问时间:10/9/2022 更新时间:10/9/2022 访问量:109

问:

我是初学者,我正在使用 android studio 在 java 中创建一个 android 应用程序。它是一个包含 2000 多个项目的 ListView。当用户点击一个项目时,他将被带到某个地图位置。当我运行该应用程序时,它说代码太大,因为方法!!我几乎阅读了所有关于这个主题的帖子,他们都建议我应该将该方法拆分为更小的方法,或者将另一个类或 (.file) 添加到我的资源中。所以我知道我的问题是在我的方法中写了太多(if 语句)行,因为我是初学者,我是手动完成的。你能不能给我看一个详细的分步指南来解决“代码太大”。 多谢

 
    package com.example.myapplicationsecond;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;

import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.example.myapplicationsecond.R;

public class MainActivity9 extends AppCompatActivity {

    ListView listView;

    String[] name = {

            "first location ",
            "second location",
            "third location",
            "fourth location",
            "fifth location",
            "sixth location",
until 2000th location

ArrayAdapter<String> arrayAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main9);
    View view = getLayoutInflater().inflate(R.layout.abs_layout, null);
    ActionBar.LayoutParams params = new ActionBar.LayoutParams(
            ActionBar.LayoutParams.WRAP_CONTENT,
            ActionBar.LayoutParams.MATCH_PARENT,
            Gravity.CENTER);

    TextView Title = (TextView) view.findViewById(R.id.actionbar_title);
    Title.setText("search here");

    getSupportActionBar().setCustomView(view,params);
    getSupportActionBar().setDisplayShowCustomEnabled(true); //show custom title
    getSupportActionBar().setDisplayShowTitleEnabled(false); //hide the default title


    getSupportActionBar().setTitle("search here");


    listView = findViewById(R.id.listview);

    arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,name);
    listView.setAdapter(arrayAdapter);


    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


            String clickedText = arrayAdapter.getItem(position);

            int positionInArray = java.util.Arrays.asList(name).indexOf(clickedText);


            if(positionInArray==0){

                Intent intent = new Intent(Intent.ACTION_VIEW , Uri.parse("http://maps.google.com/maps?saddr&daddr= 21.422503, 39.826179"));
                startActivity(intent);


            }
            if(positionInArray==1){

                Intent intent = new Intent(Intent.ACTION_VIEW , Uri.parse("http://maps.google.com/maps?saddr&daddr= 24.468333, 39.610833"));
                startActivity(intent);

            }
            if(positionInArray==2){

                Intent intent = new Intent(Intent.ACTION_VIEW , Uri.parse("http://maps.google.com/maps?saddr&daddr= N 26 23.026 E 44 59.378"));
                startActivity(intent);


            }
            if(positionInArray==3){

                Intent intent = new Intent(Intent.ACTION_VIEW , Uri.parse("http://maps.google.com/maps?saddr&daddr= 26.403737, 44.912791"));
                startActivity(intent);


            }
            if(positionInArray==4){

                Intent intent = new Intent(Intent.ACTION_VIEW , Uri.parse("http://maps.google.com/maps?saddr&daddr= N 26 36.698 E 47 34.159"));
                startActivity(intent);


            }
            if(positionInArray==5){

                Intent intent = new Intent(Intent.ACTION_VIEW , Uri.parse("http://maps.google.com/maps?saddr&daddr= N 26 05.760 E 46 29.135"));
                startActivity(intent);

until 2000th line

Android 方法

评论

0赞 CodeGorilla 10/9/2022
您不应该创建一个包含超过一千个案例的 if 语句。你需要让你的代码动态化,你从哪里得到你的谷歌地图链接?它们存放在某个地方吗?
0赞 ADM 10/9/2022
保留 a 以获取 URL 。HashMap<Integer,String>
0赞 imacro 10/9/2022
CodeGorilla:我把它们放在 MS word 的表格中,以便于复制和粘贴。ADM:谢谢,但请问我需要步骤,因为我是初学者。
0赞 ADM 10/9/2022
为了保存如此多的数据,您应该使用持久存储。数据库或文件 ..使用文件很容易,因为您只需要一次阅读所有文件。将数据保存在文件中,CSV 或 Json。然后在地图中阅读它..回答这个问题会很多,所以你需要搜索每个部分..比如如何从资产和其他东西中读取文件。
0赞 Tenfour04 10/9/2022
你真的输入了 2000 之前序数的所有单词吗?如?你对使用 Kotlin 持开放态度吗?我问的原因是,在 Kotlin 中将这些项目从文本或 CSV 文件读取到您的程序中比在 Java 中更容易。关于开始编程的一个一般提示——别忘了你是一名程序员。不应从大表中复制粘贴。作为程序员,您可以命令计算机代表您完成繁琐的工作。"one thousand nine hundred seventy-fifth location"

答:

1赞 Ivan Wooll 10/9/2022 #1

由于您是初学者,因此可以理解,这一切都非常令人不知所措,因此这里有一些提示可以帮助您。这不是一个完整的解决方案,也不是被广泛认为的最佳实践,但它将帮助您从当前位置向前迈进。我希望你能从中得到一些东西。

首先,创建一个类来表示包含有关您的位置的信息的对象。即他们的名字和 latLon。

class Location {
    private String name;
    private String latLon;

    public Location(String name, String latLon) {
        this.name = name;
        this.latLon = latLon;
    }

    public String getName() {
        return name;
    }

    public String getLatLon() {
        return latLon;
    }
}

然后,您可以将数组替换为这些项的数组,如下所示name

Location[] locations = {
        new Location("first location", "24.468333, 39.610833"),
        new Location("second location", "24.468333, 39.610833"),
        new Location("third location", "24.468333, 39.610833"),
        new Location("fourth location", "24.468333, 39.610833")
        // and so on
};

现在,您需要一种方法来提取要显示在 .为此,您可以使用以下函数ListView

private List<String> getNamesFromLocations(Location[] locations) {
    // creates a new ArrayList to hold the names of locations
    ArrayList<String> locationNames = new ArrayList<>();
    // this iterates through the array one item at a time
    for (Location location : locations) {
        // get the location name and add it to the new list defined in this function
        locationNames.add(location.getName());
    }
    // return the location names
    return locationNames;
}

您现在可以使用此函数创建位置名称列表,并使用它来初始化ArrayAdapter

List<String> names = getNamesFromLocations(locations);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, names);

在 listView 函数中,您可以获取被单击项的位置,并使用它来获取数组中相同位置的位置onItemClicklocations

Location location = locations[position];
String latLon = location.getLatLon();

然后,您可以通过将此字符串(在每个 if 语句中都相同)与特定于您所在位置的 latLon 组合在一起,使创建 Intent 的代码更干净"http://maps.google.com/maps?saddr&daddr = "

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr&daddr = " + latLon));
startActivity(intent);

评论

0赞 imacro 10/9/2022
我试着按照你告诉我的仔细去做,伙计们,甚至跟着伊万的脚步,但没有运气。代码生成了更多错误。我非常感谢伙计们,如果有人让我更容易,我将不胜感激,因为我真的被这个错误困了将近两个月。
1赞 imacro 10/26/2022
尽管我仍然没有解决我的问题,但我只想感谢 Ivan Wooll 和其他人的努力。