I'm new to Android Studio, so I followed directions to a video and an error constantly comes up that the methods ReadLines and writeLines do not exist.
I tried importing methods but none of them worked.
I assume this implementation was the one responsible for those methods, and it is in the correct location (app file) based on the instructions, but there is no error messages around it.
Video: https://www.youtube.com/watch?v=qP4U_4QvojQ&list=PLrT2tZ9JRrf6cHOlMkbmTMFt0RzpJiRGX&index=4
implementation 'commons-io:commons-io:2.6'
Here's the MainActivity.java code that uses the methods
package com.example.simpletodo;
import android.os.Bundle;
import android.os.FileUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList items;
Button btnAdd;
EditText etItem;
RecyclerView rvItems;
ItemsAdapter itemsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = findViewById(R.id.btnAdd);
etItem = findViewById(R.id.etItem);
rvItems = findViewById(R.id.rvItems);
loadItems();
ItemsAdapter.OnLongClickListener onLongClickListener = new ItemsAdapter.OnLongClickListener(){
#Override
public void onItemLongClicked(int position){
//Delete the item from the model
items.remove(position);
//Notify the adapter
itemsAdapter.notifyItemRemoved(position);
Toast.makeText(getApplicationContext(), "Item is removed", Toast.LENGTH_SHORT).show();
saveItems();
}
};
itemsAdapter = new ItemsAdapter(items);
rvItems.setAdapter(itemsAdapter);
rvItems.setLayoutManager(new LinearLayoutManager(this));
btnAdd.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String todoItem = etItem.getText().toString();
//Add item to the model
items.add(todoItem);
//Notify adapter that an item is inserted
itemsAdapter.notifyItemInserted(items.size() - 1);
etItem.setText("");
Toast.makeText(getApplicationContext(), "Item was added", Toast.LENGTH_SHORT).show();
saveItems();
}
});
}
private File getDatafile(){
return new File(getFilesDir(), "data.txt");
}
//This function will load items by reading every line of the data file
private void loadItems(){
try {
items = new ArrayList<>(FileUtils.readLines(getDatafile(), Charset.defaultCharset()));
}
catch (IOException e) {
Log.e("MainActivity", "Error reading items", e);
items = new ArrayList<>();
}
}
//This function saves items by writing them into the data file
private void saveItems(){
try {
FileUtils.writeLines(getDatafile(), items);
}
catch (IOException e){
Log.e("MainActivitiy", "Error writing items", e);
}
}
}
Try:
import org.apache.commons.io.FileUtils;
instead of
import android.os.FileUtils;
According to the documentation, android.os.FileUtils does not have readLines()
or writeLines() methods.
Related
I'm trying to access files in the android document folder. The code below works as long as the current installation of the app has created the files. After reinstalling the app or adding documents any other way the app can't access the files anymore. The file list shows up empty. Upon creating a new file, the newly created file is listed and accessible. I suspect my app is not allowed to use files in the document folder, if they are not created by the app itself - how do i change the permissions accordingly? Saving the files in the app folder is not an option.
The API version is 29.
package com.example.pos1;
import static com.example.example.pos1.*;
import static org.apache.commons.io.FilenameUtils.removeExtension;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private Button startnPButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestStoragePermission();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startnPButton = (Button) findViewById(R.id.nPButton);
startnPButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openNew();
}
});
ImportMA();
}
private void requestStoragePermission()
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE}, PackageManager.PERMISSION_GRANTED);
}
public void openNew() {
Intent intent = new Intent(this, neuesProjekt.class);
startActivity(intent);
}
public void loadexisting() {
Intent intent = new Intent(this, NeueWohnung.class);
startActivity(intent);
}
public void ImportMA()
{
ListView listView=findViewById(R.id.listview);
List<String> list = new ArrayList<>();
ArrayAdapter arrayAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1,list);
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File[] files = path.listFiles();
if (files.length>0)
{
for(int i = 0; i < files.length; i++)
{
System.out.println(files[i].getName());
list.add(removeExtension(files[i].getName()));
}
}
else
{
list.add("No elements!");
}
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String x = (String) listView.getItemAtPosition(position);
String filepath = new String (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+"/"+x+".xls");
setFilepath(filepath);
setName(x);
Toast.makeText(getApplicationContext(),
"Projekt: "+getName(), Toast.LENGTH_SHORT)
.show();
loadexisting();
}
});
}
}
I am creating a basic notes app. I took reference from a YouTube video but the video was in kotlin but I am using java. So, I am having problems in displaying the saved notes. The YouTube video was explaining the app architecture components of an android app. Here is my GitHub link to the project. And here is my MainActivity.java:
package com.test.notes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends AppCompatActivity implements NotesRVAdapter.INotesRVAdapter {
private NoteViewModel noteViewModel;
RecyclerView recyclerView;
NotesRVAdapter adapter = new NotesRVAdapter(new NotesRVAdapter.WordDiff());
EditText input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input = findViewById(R.id.input);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
noteViewModel = new ViewModelProvider(this).get(NoteViewModel.class);
noteViewModel.getAllNotes().observe(this, notes -> {
if(notes != null){
adapter.updateList(notes);
}
});
}
#Override
public void onItemClicked(Note note) {
noteViewModel.delete(note);
Toast.makeText(this, "note deleted", Toast.LENGTH_SHORT).show();
}
public void submitData(View view) {
String noteText = input.getText().toString();
if(!noteText.isEmpty()){
noteViewModel.insert(new Note(noteText));
Toast.makeText(this, "note added", Toast.LENGTH_SHORT).show();
}
}
}
Hi everybody fairly new to java and android development, I need help to get the URI from the item that the user clicks on so that it can be played.
This is all the code I have thus far please help for I have been stuck at this specific problem for some time now.
the problem is in the onItemClickListner.
package com.example.musicplayer;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
if (ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE)==PackageManager.PERMISSION_GRANTED){
Log.i("Permission ","gRANTED");
}
}
}
ListView musicListView;
ArrayList<String> musicArrayList;
ArrayAdapter<String> adapter;
MediaPlayer mediaPlayer;
Uri songUri;
public void play(View view){
}
public void pause(View view){
}
public void stop(View view){
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
this.getSupportActionBar().hide();
}catch (Exception e){
setContentView(R.layout.activity_main);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
}
musicListView= (ListView) findViewById(R.id.musicListView);
musicArrayList= new ArrayList<>();
adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,android.R.id.text1, musicArrayList);
String[] proj = { MediaStore.Audio.Media.DISPLAY_NAME };// Can include more data for more details and check it.
Cursor audioCursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null, null);
if(audioCursor != null){
if(audioCursor.moveToFirst()){
do{
int audioIndex = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
musicArrayList.add(audioCursor.getString(audioIndex));
}while(audioCursor.moveToNext());
}
}
audioCursor.close();
musicListView.setAdapter(adapter);
musicListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
songUri =//////PLEASE HELP ME GET THIS//////;
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioAttributes(
new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
);
try {
mediaPlayer.setDataSource(getApplicationContext(), songUri);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
});
}
}
I haven't yet tried this solution but in general the way pointed in this answer can solve your problem.
https://stackoverflow.com/a/10461112/3400640
So I'm relatively new to Android Studio. I'm just working on a small QR Code scanner. Basically, what I'm trying to do is add whatever the QR code result is to a text file then be able to load that text file into in another activity.
I have already added the necessary permissions to the AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
This is MainActivity.java
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.camera2.CameraManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.google.zxing.Result;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mScannerView = new ZXingScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView);
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera
}
#Override
public boolean onCreateOptionsMenu (Menu menu)
{
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int selectedId = item.getItemId();
switch (selectedId)
{
case R.id.mniHistory:
startActivity(new Intent(MainActivity.this, ResultsActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(final Result rawResult) {
// Do something with the result here
Log.e("handler", rawResult.getText()); // Prints scan results
Log.e("handler", rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode)
// Alert Box (the one that asks if you want to send)
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setTitle("Scan Result");
builder1.setMessage(rawResult.getText() + "\n" + "Would you like to send this?");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// ADD SCAN TO TEXT FILE
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("History.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(rawResult.getText());
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
// DONE ADDING TO HISTORY
dialog.cancel();
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
mScannerView.resumeCameraPreview(MainActivity.this);
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
The file is not writing for some reason. It doesn't appear in the phone's storage.
Anyway, here's ResultsActivity.java
ResultsActivity.java (Meant to display the scan history)
import android.content.Intent;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class ResultsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
ArrayList<String> completeList = new ArrayList<String>();
ListView listView1;
listView1 = (ListView) findViewById(R.id.ResultsListView);
try {
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/History.txt";
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "Cp1252"), 100);
String line;
// ArrayList<String> lines = new ArrayList<String>();
while ((line = br.readLine()) != null) {
completeList.add(line);
}
br.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, completeList);
listView1.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Am I reading the Text File into the ListView properly, by the way? Just wondering.
But anyway, my main question is writing into the internal storage and that doesn't seem to be working. Any ideas as to what is going on?
First, you shouldn't use such approach - to share simple string between components you can use many inmemory things, such as intents, services, broadcasts and so on. It is simpler to use the SharedPreferences at least.
Regarding your questions, the mistake is in this two lines of snippets:
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("History.txt", Context.MODE_PRIVATE));
At this line, you are opening stream to write data into private file (such files are stored within internal application folder).
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/History.txt";
And here you try to find the file within external storage (it is just a different folder)
So, to find your file, you can use corresponding method openFileInput
Hope, it'll help.
In this fragment I send a jsonRequest with volley to the server . and I'm setting the swipeRefreshLayout to this fragment , I want to load only new json data but when I use sendJsonRequest() method on the onRefresh() all of the json data is enabled to the recyclerView:
This is my fragment code:
package ghandak.ghandshekan.com.ghandak.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import ghandak.ghandshekan.com.ghandak.R;
import ghandak.ghandshekan.com.ghandak.adapters.PostRecyclerAdapter;
import ghandak.ghandshekan.com.ghandak.app.AppController;
import ghandak.ghandshekan.com.ghandak.models.PostData;
/**
* Created by imajid on 12/19/2015.
*/
public class TabFragment3 extends Fragment implements OnRefreshListener{
private RecyclerView allContentRecyclerView;
private String url = "http://kakdo.herokuapp.com/api/news/?format=json";
private List<PostData> postDataList = new ArrayList<PostData>();
private SwipeRefreshLayout swipeRefreshLayout;
//====================================================================================== onCreateView
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_fragment_3 , container , false);
allContentRecyclerView = (RecyclerView)view.findViewById(R.id.xmlRecyclerViewtabFragment3);
allContentRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
swipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.xml_swipe_refresh_layout_tab_fragment_3);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
//swipeRefreshLayout.setColorSchemeColors();
return view;
}
//====================================================================================== onCreate
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sendJsonRequest();
}
//====================================================================================== sendjsonRequest
private void sendJsonRequest() {
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
parseJsonResponse(response);
//==========setting adapter to the recyclerview <==
allContentRecyclerView.setAdapter(new PostRecyclerAdapter(getActivity() ,postDataList));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(request);
}
//====================================================================================== parsjsonResponse()
private void parseJsonResponse(JSONArray response) {
if(response == null){
Toast.makeText(getActivity(), "ریسپانس خالی هستش", Toast.LENGTH_SHORT).show();
return;
}else {
Log.d("parsejsonresponse", "response khali nist");
for (int i = 0 ; i < response.length() ; i++ ){
try {
//Toast.makeText(getActivity(), "ریسپانس میگیرم ", Toast.LENGTH_SHORT).show();
JSONObject currentPost = response.getJSONObject(i);
//Log.d("currentPost", "currentPost ro gereftam");
PostData postData = new PostData();
postData.setTitle(currentPost.getString("title"));
//Toast.makeText(getActivity() , currentPost.getString("title") , Toast.LENGTH_SHORT).show();
postData.setCreate(currentPost.getString("create"));
postDataList.add(postData);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onRefresh() {
sendJsonRequest();
swipeRefreshLayout.setRefreshing(false);
}
}
Now my question is in the OnRefresh method , what can I write to load only new json data, not all of the exists json.
Add this line in your code
postDataList.clear(); in your code given in bellow.
Updated:
#Override
public void onResponse(JSONArray response) {
if(response == null )
return;
postDataList.clear();
parseJsonResponse(response);
//==========setting adapter to the recyclerview <==
allContentRecyclerView.setAdapter(new PostRecyclerAdapter(getActivity() ,postDataList));
}
Note: when ever you create any kind of list max create adapter instance once in your code, After change list data you just need to call 'adapterInstance.notifyDataSetChange();'
This is the best practice instead of creating list every time it's better to refresh list items, Further info check here
add this code ,
private SwipeRefreshLayout mSwipeRefreshLayout;
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
}
}, SPLASH_DISPLAY_LENGTH);
}
});
when you want to refresh it call,
mSwipeRefreshLayout.setRefreshing(true);
swipeContainer = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeContainer);
swipeContainer.setOnRefreshListener(new OnRefreshListener()
{
#Override
public void onRefresh()
{
//clear your old data
callForData();
//swipeContainer.setRefreshing(false); use this while get data and set in you ui
}
});
// Configure the refreshing colors
swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);