java - 如何使用存储在 JSON 上的 ID 在 SearchView 过滤器之后从 ListView 打开 Activity

标签 java android json listview searchview

我是 Java 新手,我正在开发一个应用程序来完成我的大学学业。此应用程序在 ListView 上有一个 SearchView 过滤,从 JSON 获取数据。我快完成了,但我在过滤器部分之后卡住了。

在 SearchBar 上输入并且过滤器返回结果后,我无法打开从 JSON 获取 ID 的新 Intent 。我只能使用位置 ListView 编号打开 Intent (由于过滤过程,这不适用于我的需要)。

下图准确地显示了问题: Image

所以我的必要性是:使用存储在 JSON 中的 ID 打开一个 Intent ,以避免在过滤结果后更改位置 ID 的问题。

我不知道如何解决这个问题。

bean :

public class Model {
private String description;
private int id;

public Model(int id, String description) {
    this.setId(id);
    this.setDescription(description);
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

主要:

public class MainActivity extends Activity implements SearchView.OnQueryTextListener, SearchView.OnCloseListener {

private ListView list;
private ListViewAdapter adapter;
private SearchView editsearch;
public static ArrayList<Model> modelArrayList = new ArrayList<Model>();

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

    list = (ListView) findViewById(R.id.listview);
    loadDataJSON();

    adapter = new ListViewAdapter(this);
    list.setAdapter(adapter);

    editsearch = (SearchView) findViewById(R.id.search);
    editsearch.setOnQueryTextListener(this);

    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            int a = position;
            Intent myIntent = new Intent(MainActivity.this, Info.class);
            myIntent.putExtra("valor", a);
            startActivity(myIntent);
        }
    });
}

public String loadJSON(String arq) {
    String json = null;
    try {
        InputStream is = getAssets().open(arq);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}



private void loadDataJSON() {
    String arquivo = loadJSON("lista.json");
    try {
        JSONObject obj = new JSONObject(arquivo);
        JSONArray a = obj.getJSONArray("locais");
        for (int i = 0; i < a.length(); i++) {
            JSONObject item = a.getJSONObject(i);
            Model model = new Model(item.getInt("id"),item.getString("description"));
            modelArrayList.add(model);
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

@Override
public boolean onQueryTextSubmit(String query) {

    return false;
}

@Override
public boolean onQueryTextChange(String newText) {
    String text = newText;
    adapter.filter(text);
    return false;
}

@Override
public boolean onClose() {
    // TODO Auto-generated method stub
    return false;
}

适配器:

public class ListViewAdapter extends BaseAdapter {

Context mContext;
LayoutInflater inflater;
public ArrayList<Model> arraylist;

public ListViewAdapter(Context context ) {
    mContext = context;
    inflater = LayoutInflater.from(mContext);
    this.arraylist = new ArrayList<Model>();
    this.arraylist.addAll(MainActivity.modelArrayList);
}

public class ViewHolder {
    TextView name;
}

@Override
public int getCount() {
    return MainActivity.modelArrayList.size();
}

@Override
public Model getItem(int position) {
    return MainActivity.modelArrayList.get(position);
}

@Override
public long getItemId(int position) {
    return position;  
}

public View getView(final int position, View view, ViewGroup parent) {
    final ViewHolder holder;
    if (view == null) {
        holder = new ViewHolder();
        view = inflater.inflate(R.layout.listview_item, null);
          holder.name = (TextView) view.findViewById(R.id.name);
        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }
    holder.name.setText(MainActivity.modelArrayList.get(position).getDescription());
    return view;
}


public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    MainActivity.modelArrayList.clear();
    if (charText.length() == 0) {
        MainActivity.modelArrayList.addAll(arraylist);
    } else {
        for (Model mp : arraylist) {
            if (mp.getDescription().toLowerCase(Locale.getDefault()).contains(charText)) {
                MainActivity.modelArrayList.add(mp);
            }
        }
    }
    notifyDataSetChanged();
}

信息:

public class Info extends Activity {

TextView aaa, bbb;

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

    aaa = (TextView) findViewById(R.id.aaa);
    bbb = (TextView) findViewById(R.id.bbb);

    Intent mIntent = getIntent();
    int id = mIntent.getIntExtra("valor",0);

    String arquivo = loadJSON("lista.json");

    try {
        JSONObject obj = new JSONObject(arquivo);
        JSONArray a = obj.getJSONArray("locais");
        JSONObject item = a.getJSONObject(id);

        aaa.setText(item.getString("id"));
        bbb.setText("Base: "+item.getString("description"));

    } catch (JSONException e) {
        throw new RuntimeException(e);
    }

}

public String loadJSON(String arq) {
    String json = null;
    try {
        InputStream is = getAssets().open(arq);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

JSON:

{ "locais": [{ "id": "1", "description": "Text A" }, { "id": "2", "description": "Text B" }]}

最佳答案

改用int a = modelArrayList.get(position).getId()。所以你将从 JSON 中获取 id

关于java - 如何使用存储在 JSON 上的 ID 在 SearchView 过滤器之后从 ListView 打开 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56814473/

相关文章:

Java接口(interface)问题

java - 尝试从距离矩阵 api 获取距离数据总是返回 NULL

java - 如何在点击 "Update"按钮时更新存储在对象中的值 - Android?

javascript - 需要一个优化的解决方案来获取按字母顺序排列的记录集 javascript

Javascript:解析 JSON,忽略引号

java - 使用 SurfaceView 强制关闭恢复应用程序

java - 在 JaxWSClient 上启用 LoggingInInterceptor 时出现 "stream is closed"错误

java - Rekognition 客户端不断根据每个请求进行重建

android - 为什么我的图像按钮水平和垂直翻转?

json - MongoDB导入错误: Failed: error reading separator after document #1: bad JSON array format - found no opening bracket '[' in input source