How to read a text file and display in a text view? - java

When I navigate to a page in the app, I expect the text from the text file to be displayed but it isn't. Am I missing something?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
Button backButton = findViewById(R.id.button_back);
Button selectAnotherButton = findViewById(R.id.button_select_another);
TextView contentText = findViewById(R.id.content_text);
String text = "";
try {
// file to inputstream
InputStream input = getAssets().open("jokes.txt");
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
// byte buffer into a string
text = new String(buffer);
} catch (Exception e) {
System.out.println(e);
}
contentText.setText(text);
}

The code above is fine, it works as expected. The reason the text could not be seen is because there was a textview layout overlapping the file text text view layout so I couldn't see the text

contentText.invalidate();
contentText.requestLayout();

Related

(Android Studio) attempting to read file from asset folder with click of a button, returns blank

I am trying desperately to read a file from Android Studio asset folder. The file is "ok.txt" and contains the string: yo chicken mcgriddle fiddle fiddle.
Per this video: https://youtu.be/1CHDASXojNQ and stackoverflow browsing, this is the solution I came up with:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
tv_text = (TextView) findViewById(R.id.nameView);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
tv_text.setText(LoadData("ok.txt"));
}
public String LoadData(String inFile) {
String tContents = "";
try {
InputStream stream = getAssets().open(inFile);
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
tContents = new String(buffer);
} catch (IOException e) {
// Handle exceptions here
}
return tContents;
}
});
}
}
I am inclined to believe that the code works, but, it does not return the String. In the app, it returns a blank message in the place of the textview's "hello world" placeholder after clicking the button. I thought it was due to the limitation of the textview so I modified the constraint size, but the blank persists. Anybody know what's up?

Is there a way to use multiple sources for the same ImageView?

I'm trying to use an Activity which displays a random object from my array. This object is passed in from an intent.
I am trying to use an image for each of these objects and then display the correct image for the correct object.
So far I've been using the drawable folder to hold my images and then loading them in through the XML however this stops me using multiple images for the same ImageView.
I tried using imageview.setImageResource(R.drawable.imagename); but that doesn't seem to like loading in for some reason.
Do I need to make a new activity for each of the objects in this case?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random_race);
TextView name = (TextView)findViewById(R.id.raceName);
Intent secondIntent = getIntent();
Race message = (Race)secondIntent.getSerializableExtra("RACE");
ImageView image = (ImageView) findViewById(R.id.raceImage);
image.setImageResource(R.drawable.hacan);
image.setImageBitmap(imageToBitmapImage(message, image));
name.setText(message.getName());
}
Bytes to Bitmap method
public Bitmap imageToBitmapImage (Race message, ImageView image){
Bitmap bmp;
try {
FileInputStream in = new FileInputStream(message.getImageName());
BufferedInputStream buffer = new BufferedInputStream(in);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int input = buffer.read();
while (input != -1){
baos.write(input);
input = buffer.read();
}
byte[] bytes = baos.toByteArray();
bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
return bmp;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Class of each object I'm talking about.
public class Race implements Serializable {
private String name;
private String imageName; //name of file within drawable
As #XavierFalempin commented, you can't access ressources through a file stream. Using setImageResource() should work. Following this answer your onCreate() method should look something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random_race);
TextView name = (TextView)findViewById(R.id.raceName);
Intent secondIntent = getIntent();
Race message = (Race)secondIntent.getSerializableExtra("RACE");
ImageView image = (ImageView) findViewById(R.id.raceImage);
image.setImageResource(getResources().getIdentifier(message.getImageName(),
"drawable",
getPackageName()));
name.setText(message.getName());
}

Use java in Android Studio to place button to RIGHT_OF another widget

I am creating a button dynamically in Android Studio in a class that extends Fragment. I have my button created (btn) and a text that I want to go under that button (appName), but now I want to place the button next to another button that already exists (lets call it btn_2). I am having trouble finding out how to place one widget next to another using Java, and not xml. Here is what I have so far:
public void createButton (BitmapDrawable bitmapdrawable, String applicationName){
LayoutInflater inflater=null;
ViewGroup container = null;
// Get Layout home_fragment
View rootView = inflater.inflate(R.layout.home_fragment, container, false);
RelativeLayout rLayout = (RelativeLayout) rootView.findViewById(R.id.home_fragment);
// create image button with background as bitmapdrawable
ImageButton btn = new ImageButton(getActivity());
btn.setImageDrawable(bitmapdrawable);
// create textview with applicationName
TextView appName = new TextView(getActivity());
appName.setText(applicationName);
// place new button next to existing button
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF);
btn.setLayoutParams(params);
// place text under newly created button
// Put button and text in layout
rLayout.addView(btn);
rLayout.addView(appName);
}
Where I am running into errors is:
params.addRule(RelativeLayout.RIGHT_OF);
How do I pass through the ID of the EXISTING button (btn_2), that I want my new button (btn) to be placed next to?
Then, I want to fill in this empty gap
// place text under newly created button
of how to place my newly created textview (appName) under my newly created btn and under my existing btn_2. (Maybe this will be more straight forward after I figure out how to place one button next to the other.)
Here is my MainActivity. My image and string that I am passing to HomeFragment createButton method are being sent to MainActivity through a socket from another device:
// main activity (FragmentActivity provides fragment compatibility pre-HC)
public class MainActivity extends FragmentActivity implements MenuFragment.OnMenufragListener {
private Thread repeatTaskThread;
private byte[] byteArray;
// called when the activity is first created
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Listening for last installed app to create button
RepeatTask();
}
#Override
public void onMenufrag(Fragment s) {
// get body fragment (native method is getFragmentManager)
HomeFragment fragment = (HomeFragment) getSupportFragmentManager().findFragmentById(R.id.home_fragment);
// if fragment is not null and in layout, set text, else launch BodyActivity
if ((fragment!=null)&&fragment.isInLayout()) {
fragment.getView();
} else {
Intent intent = new Intent(this,HomeFragment.class);
startActivity(intent);
}
}
private void RepeatTask()
{
repeatTaskThread = new Thread()
{
public void run()
{
while (true)
{
try {
System.out.println("TRY_1");
Socket socket = new Socket("192.168.0.26", 5050);
// Get data sent through socket
DataInputStream DIS = new DataInputStream(socket.getInputStream());
System.out.println("DataInputStream Started");
// read data that got sent
String applicationName = DIS.readUTF();
// read array data for bitmap
//Drawable icon = getPackageManager().getApplicationIcon(packagename);
//System.out.println("icon" + icon);
int len = DIS.readInt();
byte[] data = new byte[len];
DIS.readFully(data, 0, data.length);
// Convert data to jpeg first then to bitmap (cant convert byte array directly to bitmap)
YuvImage yuvimage=new YuvImage(data, ImageFormat.NV21, 100, 100, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yuvimage.compressToJpeg(new Rect(0, 0, 100, 100), 80, baos);
byte[] jdata = baos.toByteArray();
// Convert to Bitmap
Bitmap bmp = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);
// Image to png in file directory
// STREAM IMAGE DATA TO FILE
// This is how I know I am correctly getting my png image (no errors here)
// convert bitmap to drawable
Drawable d = new BitmapDrawable(getResources(), bmp);
// convert drawable to bitmapdrawable
BitmapDrawable bitmapdrawable = (BitmapDrawable)d;
Log.d("tag_name", "BITMAP Drawable" + bitmapdrawable);
// Create file to stream bitmpadrawable
FileOutputStream fosIcon = openFileOutput(applicationName + ".png", Context.MODE_PRIVATE);
// compress bitmapdrawable into png and write to file that was just created
bitmapdrawable.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, fosIcon);
InputStream inputStream = openFileInput(applicationName + ".png");
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// GET FILE DIRECTORY
File imageFile = new File(getFilesDir(), applicationName + ".png");
HomeFragment createbutton = new HomeFragment();
createbutton.createButton(bitmapdrawable, applicationName);
Log.d("tag_name", "Entered Home Fragment");
socket.close();
} catch (Exception e) {
System.out.println("Exception is "+e.toString());
}
try
{
// Sleep for 5 seconds
Thread.sleep(5000);
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
};
repeatTaskThread.start();
}
}
Here is my xml for HomeFragment:
<?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:layout_margin="5dp"
android:id="#+id/home_fragment"
>
</RelativeLayout>
</HorizontalScrollView>
You have to specify the view id to make your view right of . Try -
TextView appName = new TextView(getActivity());
int id = 1001;
appName.setId(id);
params.addRule(RelativeLayout.RIGHT_OF, id);

AsyncTask - Download image - decode stream Error

I'd like to create app which allows to download a picture using URL address and next, shows it on my screen.
Unfortunately, in LogCat is showed this error:
BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: sdcard/photoalbum/download_image.jpg: open failed: ENOENT (No such file or directory)
Download's progress, which is showing on screen, works really fast. Image has 12 KB.
But I see that this picture is not downloading on my phone (sdcard).
This is caused that I couldn't decode this stream?
I would be grateful if somebody know how to resolve/fix this problem?
Here is a code:
ImageView imageView;
String image_url = "http://montco.happeningmag.com/wp-content/uploads/2015/04/run-150x150.jpg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
imageView = (ImageView) findViewById(R.id.image_view);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(image_url);
}
});
}
// how to create an assign task do download this image
class DownloadTask extends AsyncTask<String,Integer,String> // second type is Integer because this is from 'int progress', third is String because this is the return ("Download Complete...")
{
// progress bar to display this download
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Download in Progress...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
// how is the maximum size of this file, we need some variable:
int file_length = 0;
String path = params[0]; // we get this URL , 0(zero) index of this argument
// how image_url on this variable call "path"
try {
URL url = new URL(path);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
file_length = urlConnection.getContentLength();
// we need a folder to storage this download image
File new_folder = new File("sdcard/photoalbum");
if(!new_folder.exists())
{
new_folder.mkdir(); // we create new folder if 'photoalbum' doesnt exist in sdcard
}
// how to put some file inside this folder
File input_file = new File(new_folder,"downloaded_image.jpg");
// how to create input STREAM to read information data from url
InputStream inputStream = new BufferedInputStream(url.openStream(),8192); // we need input stream with some buffer. 8192(8 KB) (input stream
// now I want to read informations in one kb so I need byte variable
byte[] data = new byte[1024]; // it will read info to 1 KB
// before read information we need some variable
int total = 0;
int count = 0;
// we need output stream object to write a data
OutputStream outputStream = new FileOutputStream(input_file); // because outputStream is available in input_file
// we need write information to outputStream
while((count = inputStream.read())!=-1) //loop executes until the value became (-1)
{
// how to update value from a variable total
total += count;
outputStream.write(data,0,count); // data is available on the Byte variable data; offset; count
// how to display a progress bar: we need to call publish progress method and specify special value for this progress
int progress = (int) total*100/file_length;
publishProgress(progress);
}
// how to close Stream
inputStream.close();
outputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// after finished our job we need to return some result
return "Download Complete...";
}
#Override
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress(values[0]); // this will update the progress bar
}
#Override
protected void onPostExecute(String result) {
// after finishing job, we need to hide a progress bar
progressDialog.hide();
// how to display some result
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
// how to put image into imageView
String path = "sdcard/photoalbum/download_image.jpg";
// how to set this image in imageView
imageView.setImageDrawable(Drawable.createFromPath(path));
}
}
File new_folder = new File("sdcard/photoalbum");
if(!new_folder.exists()){
new_folder.mkdir(); // we create new folder if 'photoalbum' doesnt exist in sdcard
}
Try to modify the upper code as follow:
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
|| !Environment.isExternalStorageRemovable()) {
File new_folder = new File(Environment.getExternalStorageDirectory().toString() + File.separator + "photoalbum");
if(!new_folder.exists()){
new_folder.mkdirs(); // we create new folder if 'photoalbum' doesnt exist in sdcard
}
}

Android, change view and take screenshot

I want to change the visibility of a view from GONE to VISIBLE and take a screenshot of my whole application and save it in a file.
I'm able to take the screenshot, but the view remain not visible (GONE) in the jpeg file. The method is called from a button click:
public void onClick(View v) {
View screen = (View) findViewById(R.id.mainLayout);
//I change this from View.GONE
TextView hiddenText = (TextView) findViewById(R.id.hiddenText);
hiddenText.setVisibility(View.VISIBLE);
hiddenText.setText( "WEEEEEEEEEE" + (int)(Math.random()*10) );
View rootview = screen.getRootView();
//View rootview = getWindow().getDecorView().getRootView();
rootview.invalidate(); //I try to redraw the view without success
rootview.requestLayout();
rootview.setDrawingCacheEnabled(true);
Bitmap bitmap = rootview.getDrawingCache();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) +
File.separator + "Facebook" + File.separator + "my_screenshot.jpeg";
File file = new File(path);
file.getParentFile().mkdirs(); //if the folder doesn't exists it's created
try {
boolean asd = file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
ostream.write(bytes.toByteArray());
ostream.close();
}
catch (Exception e){
e.printStackTrace();
}
//hiddenText.setVisibility(View.GONE);
}
After that I save the file I should hide again the TextView hiddenText, but I doesn't know in which point to set the visibility GONE.

Categories