So I've been working on an App that tells you random topics to talk about. I try to read in a File and show a Text with a random Topic that was on the File. My code to do this is here:
package com.example.nosir;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import android.util.Log;
import java.util.Random;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String TAG = MainActivity.class.getSimpleName();
public static final String mPath = "example.txt";
private QuoteBank mQuoteBank;
private List<String> mLines;
Random random = new Random();
TextView text1;
String theTopic;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = findViewById(R.id.button1);
button1.setOnClickListener(this);
text1 = (TextView) findViewById(R.id.text1);
mQuoteBank = new QuoteBank(this);
mLines = mQuoteBank.readLine(mPath);
for (String string : mLines)
Log.d(TAG, string);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
text1.setText(mLines.get(random.nextInt(mLines.size())));
break;
default:
break;
}
}
}
package com.example.nosir;
import android.content.Context;
import android.content.res.AssetManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.ArrayList;
public class QuoteBank {
private Context mContext;
public QuoteBank(Context context) {
this.mContext = context;
}
public List<String> readLine(String path) {
List<String> mLines = new ArrayList<>();
AssetManager am = mContext.getAssets();
try {
InputStream is = am.open(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null)
mLines.add(line);
} catch (IOException e) {
e.printStackTrace();
}
return mLines;
}
}
But when I press the button to show the random Text, my application just closes and does nothing. I'm testing on a OnePlus6. I really don't know what's the issue. I hope that somebody can help me. Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire