import android.app.Activity;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
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 android.widget.AdapterView.OnItemClickListener;
public class textfile extends ListActivity {
// private static final int PICKFILE_RESULT_CODE = 0;
private List<String> items = null;
private File currentDirectory;
private ArrayAdapter<String> fileList;
Intent myIntent = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentDirectory = new File("/sdcard/myfolder");
getFiles(currentDirectory.listFiles());
setContentView(R.layout.main);
}
protected void onListItemClick (AdapterView<?> parent, ListView l, View v, int position, long id)
{
int selectedRow = (int)id;
currentDirectory = new File(items.get(selectedRow));
if(currentDirectory.isDirectory()){
getFiles(currentDirectory.listFiles());
} else{
//if the selected file is not a directory. get the filename
currentDirectory.getPath();
}
Intent myIntent = null;
if(((TextView) v).getText().equals("sdcard/myfolder/anskey.txt")){
myIntent = new Intent(v.getContext(), dialog.class);
}
startActivity(myIntent);
}
private void getFiles(File[] files){
items = new ArrayList<String>();
for(File file : files){
items.add(file.getPath());
}
fileList = new ArrayAdapter<String>(this,R.layout.list_item, items);
setListAdapter(fileList);
}
}
In this program i am displaying directory structure display "sdcard/myfolder" as a list.
now what i want to do is that when i click on "sdcard/myfolder/anskey.txt" dialog.class activity should open.
there is no exception but on clicking "sdcard/myfolder/anskey.txt" ,the dialog.class activity is not opening.
From what I can see, your onListItemClick() signature is not right. It should be:
protected void onListItemClick(ListView l, View v, int position, long id)
This is the first thing you will want to correct. There could be other issues with your code.
I didn't see you assigned the Listener to the listView and I didn't see you declared your class to implement onListItemClickListener as well, so the implementation of onListItemListener is just another method. Follow this simple tutorial to accomplish that
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 making an app in which you keep track of your grades. Currently, I am working on a system for adding subjects. So, I want to display the subjects on a RecyclerView. So, I have an activity for adding the subject, which gets the name of the subject, stores it in a arraylist, sends the arraylist to the RecyclerView Adapter and displays the Subject name as an item.
The issue I am facing is that, I can't seem to transfer the value of the arraylist with an Intent. I get an error in the Adapter, specifically when I try to use a command called getIntent() .
Here is the code in RecyclerAdapter.java file:
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class recyclerAdapter extends RecyclerView.Adapter<recyclerAdapter.MyViewHolder> {
private ArrayList<String> subjectList;
public recyclerAdapter(ArrayList<String> subjectList){
this.subjectList = subjectList;
}
public class MyViewHolder extends RecyclerView.ViewHolder{
private TextView subjectName;
public MyViewHolder(final View view){
super(view);
subjectName = view.findViewById(R.id.txtSubjectName);
Intent addedSubject = getIntent(); //I get the error in this line, specifically getIntent()
subjectList = addedSubject.getStringArrayListExtra("Subject");
}
}
#NonNull
#Override
public recyclerAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View subjectView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_subjects, parent, false);
return new MyViewHolder(subjectView);
}
#Override
public void onBindViewHolder(#NonNull recyclerAdapter.MyViewHolder holder, int position) {
String subject = subjectList.get(position);
holder.subjectName.setText(subject);
}
#Override
public int getItemCount() {
return subjectList.size();
}
}
Here's the code in the activity in which you add the subject name:
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
public class addSubject extends AppCompatActivity {
private ArrayList<Subjects> subjectList;
private boolean subjectAdded = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getSupportActionBar().hide();
setContentView(R.layout.activity_add_subject);
subjectList = new ArrayList<>();
}
public void addSubject (View view){
EditText editSubjectName = findViewById(R.id.editSubjectName);
Intent backToMain = new Intent(this, MainActivity.class);
Intent toAdapter = new Intent(this, recyclerAdapter.class);
String subjectName = editSubjectName.getText().toString();
if (!subjectName.equals("")){
subjectList.add(new Subjects(subjectName));
toAdapter.putExtra("Subject", subjectList);
startActivity(backToMain);
}
else
Toast.makeText(getApplicationContext(),"Invalid values, try again",Toast.LENGTH_SHORT).show();
}
Why not reinitialize the recyclerView with a new set of subjectList.
`binding.rv.adapter=recyclerAdapter(//new subject list)
Since it is an Activity specific method it's not available inside the adapter.
However if your goal is to update data there are more elegant solutions to this like notifyDataSet() or using methods inside the adapter.
However if you have a complicated implementation this answer on Passing data from an activity back to recyclerview adapter might help.
Ps: Make your class names capital. it's a coding norm
https://www.youtube.com/watch?v=D9--BF-W0AY
I did using this video (Android Studio). But it doesn't work because of "private ArrayList readSongs(File root){}", I think... All program just won't turn on....
"MainActivity.java"
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity{
private ListView listView;
private String songNames[];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
final ArrayList<File> songs = readSongs(Environment.getExternalStorageDirectory());
songNames = new String[songs.size()];
for(int i = 0; i < songs.size(); ++i){
songNames[i] = songs.get(i).getName().toString().replace(".mp3","");
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.song_layout, R.id.textView,songNames);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
startActivity(new Intent(MainActivity.this, AudioPlayer.class).putExtra("position", i).putExtra("list", songs));
}
});
}
private ArrayList<File> readSongs(File root){
ArrayList<File> arrayList = new ArrayList<File>();
File files[] = root.listFiles();
for(File file : files){
if(file.isDirectory()){
arrayList.addAll(readSongs(file));
}else{
if(file.getName().endsWith(".mp3")){
arrayList.add(file);
}
}
}
return arrayList;
}
}
scan sd card root path in main thread will consume too much time ,maybe trigger ANR,you should invoke your method asynchronized.
happy new year to all of you.
I am having a problem with the method onItemClickListener, because when I tried to toast the position and id ,in my second activity, I get zeros.
here is the code, I rely on the position of the image in the array that is why I need to get the position/id accurately.
+
I am duplicating my array in both activities because I don't know how to access it from the second activity?
MainActivity.java
package swe.trial;
import android.content.Context;
import android.widget.ImageView;
import android.view.View;
import android.view.ViewGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.AdapterView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView items = (GridView) findViewById(R.id.itemsList);
items.setAdapter(new item_adapter(this));
items.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//if an item is clicked or selceted,then go to the activity itemDetails:
Intent i= new Intent (MainActivity.this, itemDetails.class);
i.putExtra("position", position);
i.putExtra("id", id);
startActivity(i);
}
});
}
}
class item_adapter extends BaseAdapter {
Integer[] picsId = {
R.drawable.pic1,
R.drawable.pic2,
R.drawable.pic3,
R.drawable.pic4,
R.drawable.pic5,
R.drawable.pic6,
R.drawable.pic7};
private Context context;
public item_adapter(Context context) {
this.context = context;
}
public Object getItem(int position) {
return null;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imgview= new ImageView(context);
imgview.setLayoutParams(new GridView.LayoutParams(250,250));
imgview.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgview.setPadding(20,20,20,20);
imgview.setImageResource(picsId[position]);
return imgview;
}
public long getItemId(int position) {
return position;
}
public int getCount (){
return picsId.length;
}
}
itemDetails.java
package swe.trial;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
import android.net.Uri;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by good on 1/01/17.
*/
public class itemDetails extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item);
ArrayList<item> items = new ArrayList<item>();
// items item1=
// Bundle d = getIntent().getExtras();
int id=0;getIntent().getIntExtra("id",id);
int position=0;
getIntent().getIntExtra("position", position);
Toast.makeText( this, "id= " +id + " . and posistion= "+ position, Toast.LENGTH_LONG).show();
Integer[] picsId = {
R.drawable.pic1,
R.drawable.pic2,
R.drawable.pic3,
R.drawable.pic4,
R.drawable.pic5,
R.drawable.pic6,
R.drawable.pic7
};
ImageView imgview = (ImageView) findViewById(R.id.item_image);
imgview.setImageResource(picsId[id+ 1]);
TextView txt= (TextView) findViewById(R.id.pricetxtview);
txt.setText("This is the description provided." + id);
//(id);
// item item1 = {"Red rose", "#/drawable/", 1, 1.25};
// items.add(item1);
// now i will search for the array that holds the given id. and i will retrieve its info and display it again
// in the new layout.
}
}
You misunderstand the way you should use intents.
The right form is like this :
int id =getIntent().getIntExtra("id",0);
int position = getIntent().getIntExtra("position", 0);
when you use getIntExtra , the second parameter is the default value. In case there is not such value with that tag in your intent, it will return that default value.
See Google docs for more info
You have to fetch value according the following way,
int id=0;
int position=0;
i=getIntent().getIntExtra("id",id);
position= getIntent().getIntExtra("position", position);
Toast.makeText( this, "id= " +id + " . and posistion= "+ position, Toast.LENGTH_LONG).show();
Im trying to implement search bar to search an idea by title name and then press a button. Lets say I put in the search field the letter T, and clicked search.
I want the list view to update with only ideas that begin with the letter T.
Can anybody help a brother out? Thanks!
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import ideas.ideasportal.api.Idea;
import ideas.ideasportal.api.JsonHandler;
import java.util.ArrayList;
public class ViewIdeas extends AppCompatActivity {
public ArrayList<Idea> ideas = new ArrayList<Idea>();
public ListView ideasList;
Intent viewIdea;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_ideas);
viewIdea = new Intent(this, ViewIdea.class);
JsonHandler jsonHandler = new JsonHandler();
ideas = jsonHandler.handleIdeas((String)getIntent().getExtras().get("ideas"));
ideasList = (ListView)findViewById(R.id.listView);
ArrayList<String> arr = new ArrayList<>();
for(Idea idea : ideas)
{
arr.add(idea.getTitle());
}
ArrayAdapter<String> ar = new ArrayAdapter<String>(this, R.layout.list_item, arr);
ideasList.setAdapter(ar);
ideasList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Idea idea = ideas.get(position);
viewIdea.putExtra("id", idea.getId());
startActivity(viewIdea);
}
});
}
}