繁体   English   中英

如何使我的应用正确读取外部文本文件? 只显示奇怪的字符和钻石

[英]How can I get my app to read external text file correctly? Only showing weird characters and diamonds

我正在开发我的第一个应用程序。 除了显示文本文件中的随机引号之外,其他所有内容都已设置正确并且可以正常工作。 单击该按钮将显示奇怪的字符(菱形,问号等),而不显示实际的文本,除了打开和关闭占位符。

据我所知,我正确地遵循了github源码。

package drewstephensdesigns.com.dailyquotes;

import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ShareActionProvider;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private TextView mTextView;

    private String STATE_DQ;
    private static String TEXT_VALUE = "";
    private ShareActionProvider mShareActionProvider;

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

        mTextView = (TextView) findViewById(R.id.dq_view);
        //Adds scrolling to the TextView
        mTextView.setMovementMethod(ScrollingMovementMethod.getInstance());
    }

    //Code to save state on orientation change
    @Override
    public void onSaveInstanceState(Bundle outState) {
        mTextView = (TextView) findViewById(R.id.dq_view);
        outState.putString(STATE_DQ, mTextView.getText().toString());
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        mTextView = (TextView) findViewById(R.id.dq_view);
        mTextView.setText(STATE_DQ);
    }

    private AssetManager getApplicationAssets() {
        // open random quotes file
        AssetManager assetmanager = getAssets();
        return assetmanager;
    }

    private String getAssetPath(AssetManager assetmanager) {
        String[] dirs = null;
        String[] files = null;
        String path = null;

        try {
            dirs = assetmanager.list("");   //get list of files / dirs from the project 'assets' directory
            files = assetmanager.list(dirs[2]); //Directories are listed in alphabetical order so fetch the 'txt' directory
            path = dirs[2].toString() + "/" + files[0].toString();  //construct the path (there is only 1 file in the dir)
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    // Get the path for the random quote file
    private InputStreamReader getQuoteReader() throws IOException {
        // open random quotes file
        AssetManager assets = getApplicationAssets();
        String path = null;
        path = getAssetPath(assets);
        InputStream inputStream = null;

        try {
            inputStream = assets.open(path);
            Log.v("QotD path", path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStreamReader textReader = new InputStreamReader(inputStream);
        return textReader;
    }

    // Get the total number of lines in the file
    private int getFileLineCount(InputStreamReader textReader) {
        BufferedReader br = new BufferedReader(textReader);
        int lineCount = 0;
        try {
            while ((br.readLine()) != null) {
                lineCount++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return lineCount; // total number of lines in the text file
    }

    // Return a random line number from where to get the
    // corresponding quote string
    private int getRandomLineNumber(int totalLines) {
        Random rand = new Random();
        return rand.nextInt(totalLines);
    }

    private String getRandomQuote(int lineToFetch)
            throws IOException {
        //1. get path
        AssetManager assets = getApplicationAssets();
        String path = null;
        path = getAssetPath(assets);

        //2. open assets
        InputStream stream = assets.open(path);
        InputStreamReader randomQuote = new InputStreamReader(stream);

        //3. Get BufferedReader object
        BufferedReader buf = new BufferedReader(randomQuote);

        String quote = null;
        String line = null;
        int currLine = 0;

        //4. Loop through using the new InputStreamReader until a match is found
        while ((line = buf.readLine()) != null && currLine < lineToFetch) {
            currLine++;
        }

        //Got the quote
        quote = line;

        //Clean up
        randomQuote.close();
        buf.close();

        return quote;
    }

    // Set the EditText widget to display the new random quote
    private void displayQuote(String quote) {
        TextView quoteDisplay = (TextView) findViewById(R.id.dq_view);
        TEXT_VALUE = quote;
        quoteDisplay.setText(TEXT_VALUE);
    }

    // onClick handler for the button click
    public void fetch_quote(View view) throws IOException {
        // open random quotes file
        InputStreamReader textReader = getQuoteReader();

        final int totalLines = getFileLineCount(textReader);
        int lineToFetch = 0;
        String quote = null;

        // We want to get the quote at the following line number
        lineToFetch = getRandomLineNumber(totalLines);

        quote = getRandomQuote(lineToFetch);

        displayQuote(quote);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        MenuItem shareItem = menu.findItem(R.id.menu_item_share);
        mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        switch(item.getItemId()){
            case R.id.menu_item_share:
                if(TEXT_VALUE == "") {
                    Toast.makeText(this, "Nothing to share! First generate a quote by clicking the button", Toast.LENGTH_SHORT).show();
                } else {
                    Intent shareIntent = new Intent(Intent.ACTION_SEND);
                    shareIntent.setType("text/plain");
                    shareIntent.putExtra(Intent.EXTRA_TEXT, TEXT_VALUE);
                    shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Thought you might like this interesting Quote");
                    startActivity(Intent.createChooser(shareIntent, "Share the quote via..."));
                }
                break;

            case R.id.action_settings:
                Toast.makeText(getApplicationContext(), "Settings not yet implemented", Toast.LENGTH_LONG).show();
                break;
            case R.id.action_about:
                Intent aboutIntent = new Intent(this, AboutActivity.class);
                startActivity(aboutIntent);
                break;
            default:
                break;
        }

        return super.onOptionsItemSelected(item);
    }
}

这是我看到的

应用程序屏幕截图

我有一个未被使用的名为“字体”的文件夹。 我的代码正在寻找仅包含randomquote.txt文件的资产文件夹。 由于其中存在额外的文件夹,因此无法找到txt文件。 删除了该文件夹,因为它没有被使用,保存,繁荣和进步。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM