0

我想设置我的代码,当我单击列表视图中的一行时,它会从文本文件(来自记事本或 Access)返回文本。这是可能的还是需要不同的格式。

这是我到目前为止的代码,我相信它应该只是从文件中提取的一两行代码。这是我的主要活动代码:`

Toolbar toolbar;
ListView listView;


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

    toolbar=(Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle(getResources().getString(R.string.app_name));
    listView=(ListView) findViewById(R.id.listView);

    ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_list_item_1,
            getResources().getStringArray(R.array.Materials));

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent intent= new Intent(MainActivity.this, SecondActivity.class);
            intent.putExtra("MaterialName", listView.getItemAtPosition(i).toString());
            startActivity(intent);
        }
    });
    listView.setAdapter(mAdapter);
}

这是我的第二个活动代码:

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

    mToolbar = (Toolbar) findViewById(R.id.toolbar1);
    material = (TextView) findViewById(R.id.textView);

    Bundle bundle = getIntent().getExtras();
    if(bundle != null) {
        mToolbar.setTitle(bundle.getString("MaterialName"));
        if(mToolbar.getTitle().toString().equalsIgnoreCase("4140")){
            //how do I get it to return the information from a text file
        }
    }

}`

查看答案中的链接后,我的第二个活动现在看起来像这样:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    BufferedReader reader = null;

   try {
       reader = new BufferedReader(
               new InputStreamReader(getAssets().open("4140.txt")));

       String mLine;
       while ((mLine = reader.readLine()) != null) {
           text.append(mLine);
           text.append('\n');
       }
   } catch (IOException e) {
       Toast.makeText(getApplicationContext(), "Error reading file!", Toast.LENGTH_LONG).show();
       e.printStackTrace();
   } finally {
       if (reader != null) {
       try {
           reader.close();
       } catch (IOException e) {

       }
    }

    TextView output= (TextView) findViewById(R.id.toolbar1);
    output.setText((CharSequence)text);
   }

}

}

当我运行模拟器时,我的主要活动正确出现。 我项目的主要活动

当我单击列表值 4140 而不是使用工具栏和带有我文件中的文本的 textview 显示第二个活动时,它停止工作。

另外我似乎遗漏了我想将文本文件链接到特定的列表值。当我对图像执行此操作时,当我单击列表值时,我在第二个活动上的工具栏重复了该列表值,然后根据我的工具栏所说的内容,它从我的可绘制文件中提取了正确的图像。似乎我缺少将每个列表值链接到其特定且正确的文本文件的部分。

4

1 回答 1

0

在第二个活动中,您应该使用阅读器来获取 txt 文件字符串。

检查这个关于阅读 txt 并输出为 textview 的问答

关于打开 Access 数据库,这是一个涉及读者的大话题,并且可能是在其上运行查询的一种方式。另一个问题解决了这个问题。

PS:很抱歉只添加了链接,但我认为他们最好地解释了每一点。

于 2017-11-17T14:52:56.650 回答