I am working on a project. My program shows a video by videoview and get values from an excel file. I am having difficulty in showing the values one by one. I am trying to use some delay methods. I have used Thread.sleep and SystemClock.sleep methods but they freeze the entire app and phone. Now I am trying to use handler method. I don't receive any error but there is no delay. I am putting my code below.
If anyone can help me with this delay, I will be very happy.
package com.example.exceldeneme;
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.MediaController;
import android.widget.VideoView;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.String;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class MainActivity<number_cars> extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoView videoView = findViewById(R.id.video_view);
Button button = findViewById(R.id.button);
TextView text_cars = findViewById(R.id.textEmpty);
TextView text_total_lots = findViewById(R.id.textTotalLots);
readData();
int number_of_park = 100;
text_total_lots.setText(String.valueOf(number_of_park));
int counter = 0;
String videoPath = "android.resource://" + getPackageName() + "/" + R.raw.camera_out;
Uri uri = Uri.parse(videoPath);
videoView.setVideoURI(uri);
MediaController mediaController = new MediaController(this);
videoView.setMediaController(mediaController);
mediaController.setAnchorView(videoView);
for (String i : number_of_cars.get(0)){
counter = counter + 1 ;
}
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int counter = 0;
for (String i : number_of_cars.get(0)){
counter = counter + 1 ;
}
for (int i = 1; i < counter-1;i= i +1){
String count_park = number_of_cars.get(0)[i];
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
text_cars.setText(count_park);
}
}, 1000);
//SystemClock.sleep(1000); //ms
Log.d("Selam","SORUN YOK");
}
}
});
}
private ArrayList<String[]> number_of_cars = new ArrayList<String[]>();
private void readData() {
InputStream is = getResources().openRawResource(R.raw.numberofcars);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8"))
);
String line = "";
try {
while(((line = reader.readLine()) != null)) {
String[] tokens = line.split(",");
number_of_cars.add(tokens);
Log.d("MyActivity","Just created"+ Arrays.toString(tokens));
}
}
catch (IOException e) {
Log.wtf("MyActivity","Error reading data file on line" + line, e);
e.printStackTrace();
}
}
}
for the isolated issue you probably want :
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
text_cars.setText(count_park);
}
}, 1000 * i);
But you should really have a single instance Handler and post all Runnable objects to it, with a way to remove all pending Runnable, if any when ui is destroyed using : Handler::removeCallbacksAnMessages(null) in the relevant hook method like onDestroy.
Related
I'm trying to create an app that queries a site of cat images, saves them to the android device if the JSON ID is unique, and then display them from the device in a slideshow format. Despite everything my AsyncTask doesn't seem to actually be executing. Debugger confirms a network connection is established and doesn't feed me back any errors so I have no idea what's wrong with my code. Hoping someone can help! Code is below:
package com.example.lab2;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.content.AsyncTaskLoader;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ProgressBar;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Array;
import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CatImages req = new CatImages();
req.execute();
}
class CatImages extends AsyncTask<String, Integer, String> {
ArrayList<String> ids = new ArrayList<String>();
ContextWrapper cw = new ContextWrapper(getApplicationContext());
Bitmap images;
String id;
ImageView imageView = findViewById(R.id.imageView);
ProgressBar progressBar = findViewById(R.id.progressBar);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
boolean on = true;
#Override
protected String doInBackground(String... strings) {
while(on == true) {
try {
URL url = new URL("https://cataas.com/cat?json=true");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream response = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(response, "UTF-8"), 8);
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
builder.append(line + "\n");
}
String result = builder.toString();
JSONObject image = new JSONObject(result);
id = image.getString("id");
ids.add(id);
for (String element : ids) {
if (element.contains(id)) {
return null;
} else {
images = BitmapFactory.decodeStream(response);
File path = new File(directory, id + ".jpg");
FileOutputStream outputStream = new FileOutputStream(path);
images.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.flush();
outputStream.close();
ids.add(id);
}
}
for (int i = 0; i < 100; i++) {
try {
publishProgress(i);
Thread.sleep(30);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException | JSONException e) {
return null;
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
for(String element : ids) {
if(element.contains(id)) {
File openedPic = new File(directory, id + ".jpg");
try {
Bitmap opener = BitmapFactory.decodeStream(new FileInputStream(openedPic));
imageView.setImageBitmap(opener);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onPostExecute(String fromDoInBackground) {
super.onPostExecute(fromDoInBackground);
}
}
}
Try changing !=null to ==null in your second while loop.
Also you just need while(on) in your first while loop.
Let me know if anything changes.
I'm trying to build an app for school that queries a website full of random cat pictures and displays them on an emulated android TV. My code looks right, but when I run it I get the spinning wheel showing it's loading and nothing else. I'm not sure what exactly is missing, but hoping someone can point me in the right direction. Code is below:
package com.example.lab2;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.content.AsyncTaskLoader;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.widget.ImageView;
import android.widget.ProgressBar;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Array;
import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> ids = new ArrayList<String>();
class CatImages extends AsyncTask<String, Integer, String> {
ContextWrapper cw = new ContextWrapper(getApplicationContext());
Bitmap images;
String id;
ImageView imageView = findViewById(R.id.imageView);
ProgressBar progressBar = findViewById(R.id.progressBar);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
boolean on = true;
#Override
protected String doInBackground(String... strings) {
while(on == true) {
try {
URL url = new URL("https://cataas.com/cat?json=true");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream response = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(response, "UTF-8"), 8);
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
builder.append(line + "\n");
}
String result = builder.toString();
JSONObject image = new JSONObject(result);
id = image.getString("id");
for (String element : ids) {
if (element.contains(id)) {
return null;
} else {
images = BitmapFactory.decodeStream(response);
File path = new File(directory, id + ".jpg");
FileOutputStream outputStream = new FileOutputStream(path);
images.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.flush();
outputStream.close();
ids.add(id);
}
}
for (int i = 0; i < 100; i++) {
try {
publishProgress(i);
Thread.sleep(30);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException | JSONException e) {
return null;
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
for(String element : ids) {
if(element.contains(id)) {
File openedPic = new File(directory, id + ".jpg");
try {
Bitmap opener = BitmapFactory.decodeStream(new FileInputStream(openedPic));
imageView.setImageBitmap(opener);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
}
I am trying to read a text file from SD-Card in a Runnable called PcmDataReader and updating a TextView statusTextView , accordingly in the UI-Thread.
I am using a handler to pass the messages from PcmDataReader to the UI-Thread.
In order to be able to observe the change of statusTextView I have put a Thread.sleep(5000) in PcmDataReader.
The issue is that the UI-Thread is blocked until the file i/o & the sleep are finished & the final update i.e. "File Reading Complete.." is only shown on statusTextview.
What am I missing here ? Following is my code:
MainActivity.java:
package com.example.pcmreader;
import android.Manifest;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TextView statusTextView ;
priavte Button updateButton;
private PcmDataReader pcmData = new PcmDataReader();
private static Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
handler = new Handler()
{
#Override
public void handleMessage (Message message)
{
String msg = (String) message.obj;
if (statusTextView != null)
statusTextView.setText(msg);
}
};
setContentView(R.layout.main);
statusTextView= (TextView) findViewById(R.id.statusTextView);
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE }, 100);
updateButton.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
statusTextView.setText("Initiating Read .. ");
pcmData.run();
}
public static Handler getHandler ()
{
return handler;
}
}
PcmDataReader.java:
package com.example.pcmreader;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class PcmDataReader implements Runnable
{
private int [] samples = new int[6000];
private int i;
private boolean completedReading;
private File sdcard = Environment.getExternalStorageDirectory();
private File file = new File(sdcard,"rishav_log.txt");
#Override
public void run()
{
i=0;
completedReading = false;
try
{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
Handler uiHandler= MainActivity.getHandler();
Message msg = uiHandler.obtainMessage();
msg.obj="File openned, Reading data..";
uiHandler.sendMessage(msg);
while ((line = br.readLine()) != null)
samples[i++]=Integer.parseInt(line);
Thread.sleep(5000); //dummy sleep to observe the update of textView in UI thead
br.close();
completedReading = true;
msg = uiHandler.obtainMessage();
msg.obj="File Reading Complete..";
uiHandler.sendMessage(msg);
}
catch (IOException e)
{
Log.i("file read",e.getMessage());
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
Calling runnable should be in separate thread.
Replace
pcmData.run();
to
Thread t1 =new Thread(pcmData);
t1.start();
The UI thread freezes because you call the Thread.sleep() in the same thread:
#Override
public void onClick(View view) {
statusTextView.setText("Initiating Read .. ");
pcmData.run(); // PcmDataReader.run() will happen in the UI thread
}
The fix is relatively easy:
#Override
public void onClick(View view) {
statusTextView.setText("Initiating Read .. ");
ExecutorService executor = Executors.newSingleThreadExecutor(); // this can come from somplace else.
// Actually, it better comes from someplac else.
executor.submit(pcmData); // this is how to run in in a background thread.
// executor.shutdown(); // this is necessary only if you create the executor in the same method.
// Otherwise, creating and killing background threads is a matter of your apps strategy.
}
I've tried using both SharedPrefrences and also saving to internal storage but I cannot get the results I want. The only results I have achieved are crashes.
I have an app that generates a custom password based on user options, it then enters those password into an Arraylist if the user clicks a button to save the password. However, when the app closes all data is lost.
How do I save the populated ArrayList or ListView so when the user clicks views passwords they can see their previously saved passwords?
* MAIN ACTIVITY JAVA *
package com.jrfapplications.passgen;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import static com.jrfapplications.passgen.SettingsPage.CustPass;
import static com.jrfapplications.passgen.SettingsPage.FBPass;
import static com.jrfapplications.passgen.SettingsPage.custword;
import static com.jrfapplications.passgen.SettingsPage.custwordend;
import static com.jrfapplications.passgen.SettingsPage.isEndWordChecked;
import static com.jrfapplications.passgen.SettingsPage.isHighCaseChecked;
import static com.jrfapplications.passgen.SettingsPage.isNumbChecked;
import static com.jrfapplications.passgen.SettingsPage.isSpecChecked;
import static com.jrfapplications.passgen.SettingsPage.isStartCustWordChecked;
import static com.jrfapplications.passgen.SettingsPage.passLength;
public class MainActivity extends AppCompatActivity implements Serializable {
//Buttons
Button btnGoToSet;
Button btnGenPass;
Button btnViewPass;
Button btnSavePass;
//TextView
TextView passView;
//Saved Pass Array
static ArrayList<String> SavedCustomPasswords = new ArrayList<>();
static ArrayList<String> SavedFacebookPasswords = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Find Buttons
btnGoToSet = (Button) findViewById(R.id.settingsbtn);
btnGenPass = (Button) findViewById(R.id.genpass);
btnViewPass = (Button) findViewById(R.id.viewpassbtn);
btnSavePass = (Button) findViewById(R.id.SavePassBtn);
//Find TextView
passView = (TextView) findViewById(R.id.pwEditTxt);
//Button Functions
btnGoToSet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, SettingsPage.class));
}
});
btnGenPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
generatePassword(generateCharSet());
}
});
btnSavePass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (CustPass == 1){
if (SavedCustomPasswords.contains(passView.getText().toString())){
Toast.makeText(getApplicationContext(), "Password Already Saved", Toast.LENGTH_SHORT).show();
}else{
SavedCustomPasswords.add(passView.getText().toString());
Toast.makeText(getApplicationContext(), "Password Saved", Toast.LENGTH_SHORT).show();
}
}
if (FBPass == 1){
if (SavedFacebookPasswords.contains(passView.getText().toString())){
Toast.makeText(getApplicationContext(), "Password Already Saved", Toast.LENGTH_SHORT).show();
}else{
SavedFacebookPasswords.add(passView.getText().toString());
Toast.makeText(getApplicationContext(), "Password Saved", Toast.LENGTH_SHORT).show();
}
}
}
});
btnViewPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, view_pass.class));
}
});
}
public char[] generateCharSet() {
String numbers = "0123456789";
String special = "!£$%^&*()";
String alphabetsLower = "abcdefghijklmnopqrstuvwxyz";
String alphabetsUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Add lower alphabets by default
StringBuilder finalCharset = new StringBuilder(alphabetsLower);
// Add special chars if option is selected
if (isSpecChecked == 1) {
finalCharset.append(special);
}
// Add upper case chars if option is selected
if (isHighCaseChecked == 1) {
finalCharset.append(alphabetsUpper);
}
// Add numbers if option is selected
if (isNumbChecked == 1) {
finalCharset.append(numbers);
}
// build the final character set
return finalCharset.toString().toCharArray();
}
public void generatePassword(char[] charset) {
final StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < passLength; i++) {
char c = charset[random.nextInt(charset.length)];
sb.append(c);
}
if (isStartCustWordChecked == 1 && isEndWordChecked == 1){
final String output = custword + sb.toString() + custwordend;
passView.setText(output);
}else if (isStartCustWordChecked == 1){
final String output = custword + sb.toString();
passView.setText(output);
}else if (isEndWordChecked == 1){
final String output = sb.toString() + custwordend;
passView.setText(output);
}else
{
final String output = sb.toString();
passView.setText(output);
}
}
}
* VIEW PASS JAVA *
package com.jrfapplications.passgen;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class view_pass extends AppCompatActivity {
private ListView mListView1, mListView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pass);
mListView1 = (ListView)findViewById(R.id.listView1);
mListView2 = (ListView)findViewById(R.id.listView2);
mListView1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, MainActivity.SavedCustomPasswords));
mListView2.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, MainActivity.SavedFacebookPasswords));
ListUtils.setDynamicHeight(mListView1);
ListUtils.setDynamicHeight(mListView2);
}
public static class ListUtils {
public static void setDynamicHeight(ListView mListView) {
ListAdapter mListAdapter = mListView.getAdapter();
if (mListAdapter == null) {
// when adapter is null
return;
}
int height = 0;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(mListView.getWidth(), View.MeasureSpec.UNSPECIFIED);
for (int i = 0; i < mListAdapter.getCount(); i++) {
View listItem = mListAdapter.getView(i, null, mListView);
listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
height += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = mListView.getLayoutParams();
params.height = height + (mListView.getDividerHeight() * (mListAdapter.getCount() - 1));
mListView.setLayoutParams(params);
mListView.requestLayout();
}
}
}
This can be done by simply storing the generated password into sqlite database. https://developer.android.com/training/basics/data-storage/databases.html
You can also use cursor loaders for a better performance.
https://developer.android.com/guide/components/loaders.html
Try using a DBMS, if you want it stored locally, I would recommend SQL, or cloud-based system like Firebase
Shared preferences and Gson, much simple.
I used shared preferences to to save my ArrayLists on close thanks for the direction guys!
Using this for my answer:
Android: keep values in list after app shutdown
static ArrayList<String> SavedCustomPasswords = new ArrayList<>();
SavedCustomPasswords = getArray();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, SavedCustomPasswords);
adapter.notifyDataSetChanged();
public boolean saveArray() {
SharedPreferences sp = this.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
SharedPreferences.Editor mEdit1 = sp.edit();
Set<String> set = new HashSet<String>();
set.addAll(SavedCustomPasswords);
mEdit1.putStringSet("list", set);
return mEdit1.commit();
}
public void onStop() {
saveArray();
super.onStop();
}
public ArrayList<String> getArray() {
SharedPreferences sp = this.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
//NOTE: if shared preference is null, the method return empty Hashset and not null
Set<String> set = sp.getStringSet("list", new HashSet<String>());
return new ArrayList<String>(set);
}
I'm getting a null pointer exception on the line marked with /Here/ in my code. I've spent about 2 hours looking up the AssetManager and how to use it, etc, but still can't figure out why it's null. I've called getAssets() by itself, from the context and from the resources but still I'm getting null. Can anyone help me out here?
Thanks.
package com.hamc17.CatFacts;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class FactsActivity extends Activity{
Context context;
Resources res;
#Override
public void onCreate(Bundle savedInstanceBundle){
super.onCreate(savedInstanceBundle);
context = getApplicationContext();
res = context.getResources();
Button getFactButton = (Button) findViewById(R.id.getFactButton);
getFactButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast toastMessageOnClick = new Toast(FactsActivity.this);
toastMessageOnClick.setText(getFact());
if((toastMessageOnClick.toString()).length()>50)
{
toastMessageOnClick.setDuration(10);
}
else
{
toastMessageOnClick.setDuration(Toast.LENGTH_LONG);
}
toastMessageOnClick.show();
}
});
}
String[] factArray = getFactsFromTextFile().split(";");
private String getFactsFromTextFile(){
/*Here*/ AssetManager assMan = context.getAssets();
try{
BufferedReader buff = new BufferedReader(new InputStreamReader(assMan.open("facts.txt")));
String line;
StringBuilder build = new StringBuilder();
while((line = buff.readLine()) != null)
{
build.append(line).append(System.getProperty("line.seperator"));
}
return build.toString();
}
catch (IOException e)
{
Toast toastMessage = new Toast(getApplicationContext());
toastMessage.setText(e.toString() + "\n Whoops, there was an error! ");
toastMessage.show();
return "";
}
finally
{
try{
assMan.close();
}
catch (Exception e)
{
//Whatever Trevor
}
}
}
private String getFact(){
String randomFactString = "";
int factCount = factArray.length;
Random rng = new Random();
int randomNum = rng.nextInt()*factCount;
randomFactString = factArray[randomNum];
return randomFactString;
}
}
You are missing setContentView(R.layout.mylayout);
#Override
public void onCreate(Bundle savedInstanceBundle){
super.onCreate(savedInstanceBundle);
setContentView(R.layout.mylayout);
Button getFactButton = (Button) findViewById(R.id.getFactButton);
findViewById looks for a resource with the id in the current inflated layout. So you should set the content of your layout to the activity before initializing views
Also you can use
res = getResources();
Instead of creating a local variable to get the Context of the Activity just use getBaseContext(); each time you want to get the reference to the Context.
So something like this instead:
AssetManager assMan = getBaseContext().getAssets();