I'm creating an app which has a csvfile stored in its Raw resource folder and when I click on a button in main Activity , it should print the data of the csvfile in second Activity. But when I launch the app and then launch the second activity using a button ,its output is blank...
I have tried using various codes from stack overflow but I was not able to achieve the desired result. My csv File is really long, but I have kept a portion of it in here , so pls bear with me ;-) :
6200,30,10,9
6200 N,30,10,9
6200 NR,30,10,9
6200 ZNR,30,10,9
6200 ZZNR,30,10,9
6300,35,10,11
6300 2RS,35,10,11
6300 RS,35,10,11
6300 Z,35,10,11
6300 ZZ,35,10,11
6201,32,12,10
6201 2RS,32,12,10
6201 N,32,12,10
6201 NR,32,12,10
6201 RS,32,12,10
6201 Z,32,12,10
6201 ZNR,32,12,10
6201 ZZ,32,12,10
This is my code:-
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = findViewById(R.id.button1);
Button button2 = findViewById(R.id.button2);
Button button3 = findViewById(R.id.button3);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SecondActivity();
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ThirdActivity();
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FourthActivity();
}
});
}
public void SecondActivity() {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
public void ThirdActivity(){
Intent intent = new Intent(this, ThirdActivity.class);
startActivity(intent);
}
public void FourthActivity(){
Intent intent = new Intent(this,FourthActivity.class);
startActivity(intent);
}
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
InputStream inputStream;
String[] data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
inputStream = getResources().openRawResource(R.raw.bearingdata);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while ((csvLine = reader.readLine()) != null)
{
data=csvLine.split(",");
try{
Log.e("Data ",""+data[0]) ;
Log.e("Data ",""+data[0]+""+data[1]+""+data[2]) ;
}catch (Exception e){
Log.e("Problem",e.toString());
}
}
}
catch (IOException ex) {
throw new RuntimeException("Error in reading CSV file: "+ex);
}
}
So am I missing something like a create a separate java class for the csv file or is some of my code missing something??? Pls help , because I am just trying to learn some coding and also do this correctly.
Also by the way, I want to display the csv file in a list view on SecondActivity.
#Nachiketa,
I have tried your shared code and modified using asset manager and able to see the data in the logcat. Please see the below code,
AssetManager am = getAssets();
try {
InputStream is = am.open("one.csv");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String csvLine;
while ((csvLine = reader.readLine()) != null)
{
data=csvLine.split(",");
try{
Log.e("Data ",""+data[0]) ;
Log.e("Data ",""+data[0]+""+data[1]+""+data[2]) ;
}catch (Exception e){
Log.e("Problem",e.toString());
}
}
} catch (IOException e) {
e.printStackTrace();
}
Please check this and mark as answered, if solves your problem.
Thanks
Related
In the SecondActivity, it has an ImageViewand a Button
public class SecondActivity extends AppCompatActivity
{
private ImageView galleryImage;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
galleryImage = findViewById(R.id.galleryImage);
Button openGalleryButton = findViewById(R.id.openGalleryButton);
openGalleryButton.setOnClickListener(view ->
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
activityResultLauncher.launch(intent);
});
/*...*/
}
}
for the activityResultLauncher, it is an ActivityResultLauncher that I used to open gallery and pick an Image.
ActivityResultLauncher<Intent> activityResultLauncher =
registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result ->
{
if (result.getResultCode() == Activity.RESULT_OK)
{
Intent data = result.getData();
if (data != null)
{
galleryImage.setImageURI(data.getData());
try
{
openFileOutput("uri", MODE_PRIVATE).write((data.getData() + "\n").getBytes());
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
});
As you can see, this not only shows the image that users pick, but also stores the uri string into a file for later use. But when I change to ThirdActivity, there is always a SecurityException stop me.
/*SecondActivity.java*/
Button showPickedButton = findViewById(R.id.showPickedButton);
showPickedButton.setOnClickListener(view ->
{
Intent thirdActivity = new Intent(SecondActivity.this, ThirdActivity.class);
thirdActivity.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(thirdActivity);
});
/*ThirdActivity.java*/
public class ThirdActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
LinkedList<String> uriStrings = new LinkedList<>();
String readImageURI;
try
{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(openFileInput("uri"), StandardCharsets.UTF_8));
while (true)
{
readImageURI = bufferedReader.readLine();
if (readImageURI != null)
uriStrings.add(readImageURI);
else
break;
}
}
catch (IOException e)
{
e.printStackTrace();
}
LinearLayout imagesList = findViewById(R.id.imagesList);
uriStrings.forEach(imageURIString ->
{
ImageView imageView = new ImageView(this);
imageView.setImageURI(Uri.parse(imageURIString));
imageView.setAdjustViewBounds(true);
imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
imagesList.addView(imageView);
});
}
}
The exception message:
As you can see, this not only shows the image that users pick, but also stores the uri string into a file for later use
That will not work with ACTION_PICK.
But when I change to ThirdActivity, there is always a SecurityException stop me.
For the purposes of using the Uri in the same process invocation as when you got it, you can pass the Uri along in the Intent:
Intent thirdActivity = new Intent(SecondActivity.this, ThirdActivity.class);
thirdActivity.setData(theImageUriThatWeAreTalkingAbout);
thirdActivity.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(thirdActivity);
However, that will not help for durable access via your persisted Uri value. Either get rid of that, or:
Switch to ACTION_OPEN_DOCUMENT instead of ACTION_PICK, and
Call takePersistableUriPermission() on a ContentResolver when you get the image Uri value
See this blog post for more.
I want to share my mp3 file with External Storage on the WhatsApp application, but when I open my application and press the button, it throws it from the application. I have codes below. Can you tell me my error?`
Button paylas ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
paylas = (Button)findViewById(R.id.paylas);
paylas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra("sms_body", "bod of sms");
sendIntent.setType("*/*");
sendIntent.setClassName("com.mec.enes", "com.mec.enes.MainActivity");
final File file1 = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"sesler");
Uri uri = Uri.fromFile(file1);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(sendIntent, ""));
}
});
}
public void hariciYaz(){
try {
File dosyaYolu = Environment.getExternalStorageDirectory();
File dosya = new File(dosyaYolu , "sesler");
if(!dosya.exists()){
dosya.createNewFile();
}
FileWriter fw = new FileWriter(dosya);
BufferedWriter yazici = new BufferedWriter(fw);
yazici.write("src\\main\\res\\raw\\helikopter.mp3");
yazici.flush();
yazici.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}`
yazici.write("src\main\res\raw\helikopter.mp3"); is there an error in this code? Is the audio file in the raw folder saved to external storage like this?
Hello I have wrote this code to read my csv and when I click a button I get an output. The thing is the only line that gets printed is the final row of the csv. How can I modify my code so with each and every click I get next line?
``InputStream inputStream;
String[] ids;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.textView);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputStream = getResources().openRawResource(R.raw.dating);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try{
String csvLine;
while((csvLine = reader.readLine())!=null){
ids = csvLine.split(",");
try{
textView.setText(ids[3]+ids[4]);
}catch (Exception e){
Log.e("Unknown exception", e.toString());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
Move the:
inputStream = getResources().openRawResource(R.raw.dating);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
out off the OnClickListener.
That's all.
I wish I could get the content that the user enters into a text file, and then read it when the user logs in, yes this is the password. Preferences much use shared or sqlite but I already not happen with a file ... So when I press the button, the content should be written in a text file. Or when I do with the file explorer, nothing .. Thanks for your help! Here is my code:
public class MDPinterne extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mdpinterne);
Button button = (Button) findViewById((R.id.button3));
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText mdp = (EditText) findViewById(R.id.editText2);
String chmdp = mdp.getText().toString();
try {
// open myfilename.txt for writing
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("mdpsecurity",0));
// write the contents on mySettings to the file
out.write(chmdp);
// close the file
out.close();
} catch (java.io.IOException e) {
//do something if an IOException occurs.
}
}
});
}
}
Try with this:
File root = new File(Environment.getExternalStorageDirectory(), "YOUR_FOLDER");
if (!root.exists()) {
root.mkdirs();
}
try
{
File mFile;
mFile = new File(root, "YOUR_FILE_NAME.TXT");
mFileWriter = new FileWriter(mFile);
mFileWriter.append("YOUR TEXT");
mFileWriter.flush();
mFileWriter.close();
}
catch(IOException e) {
e.printStackTrace();
}
And don't forget permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I have an HTTP GET that is receiving information from a URI. The URI is for Google Shopping.
https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q=digital+camera&alt=atom
(Left my key out).
Is there a way that I can change it from
q=digital+camera
to anything a user puts in an EditText?
So basically, I want the EditText to change what is searched on Google Shopping.
First screen, ProductSearchEntry with EditText for search query:
Code for ProductSearchEntry
public class ProductSearchEntry extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.productsearchentry);
Button search = (Button) findViewById(R.id.searchButton);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent searchIntent = new Intent(getApplicationContext(), ProductSearch.class);
startActivity(searchIntent);
}
});
}
}
Then, I have a second class, ProductSearch, with no picture, but just this code:
public class ProductSearch extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.productsearchresults);
EditText searchQuery = (EditText) findViewById(R.id.searchQuery);
ProductSearchMethod test = new ProductSearchMethod();
String entry;
TextView httpStuff = (TextView) findViewById(R.id.httpTextView);
try {
entry = test.getSearchData(searchQuery.getText().toString());
httpStuff.setText(entry);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Which references the ProductSearchMethod class which consists of a TextView that is changed to the code recieved in the HTTP GET:
Code:
public class ProductSearchMethod {
public String getSearchData(String query) throws Exception{
BufferedReader in = null;
String data = null;
try{
HttpClient client = new DefaultHttpClient();
URI site = new URI("https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q="+query.replace(" ","+")+"&alt=atom");
HttpGet request = new HttpGet();
request.setURI(site);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.seperator");
while((l = in.readLine()) !=null){
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}finally{
if (in != null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}
ProductSearchMethod comes up great, but it doesn't change the text from "Loading Items" to the website code. I had it working before but then I tried to edit what it searched (all this ^) and now it doesn't change.
Make changes in your code like
public class ProductSearchEntry extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.productsearchentry);
EditText etSearch = (EditText) findViewById(id of your edittext);
Button search = (Button) findViewById(R.id.searchButton);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//while calling intent
Intent searchIntent = new Intent(getApplicationContext(), ProductSearch.class);
searchIntent.putExtra("searchText",etSearch.getText().toString());
startActivity(searchIntent);
}
});
}
}
and another activity like this,
public class ProductSearch extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.productsearchresults);
String searchQuery = getIntent().getStringExtra("searchText");
ProductSearchMethod test = new ProductSearchMethod();
String entry;
TextView httpStuff = (TextView) findViewById(R.id.httpTextView);
try {
entry = test.getSearchData(searchQuery);
httpStuff.setText(entry);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Yeah... Change your getSearchData() method to include a string as a parameter
public String getSearchData(String query) throws Exception{
Then, insert that string into the query URL, replacing spaces with "+". You may want to do further conditioning to the string, for instance URL encoding it.
URI site = new URI("https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q="+query.replace(" ","+")+"&alt=atom");
In your XML, create a button that contains the following line:
android:onClick="search"
In your ProductSearch activity, add the following method, and move the code in onCreate into it. You will also need to create an EditText in your XML for input.
public void search(View v)
{
EditText searchQuery = (EditText) findViewById(R.id.searchQuery);
ProductSearchMethod test = new ProductSearchMethod();
String returned;
try {
returned = test.getSearchData(searchQuery.getText().toString());
httpStuff.setText(returned);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Finally, you will probably want to read up on running asynchronous tasks so that the query won't freeze your app while performing.
May be I got you wrong, but why don't you just pass it as a parameter in
getSearchData() => getSearchData(string query)
Then you can change the line
URI site = new URI("https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q=digital+camera&alt=atom");
to
URI site = new URI("https://www.googleapis.com/shopping/search/v1/public/products?key=key&country=US&q=+ URLEncoder.encode(query, "UTF-8")+&alt=atom");
Check out http://androidforums.com/developer-101/528924-arduino-android-internet-garage-door-works-but-could-use-input.html I use Asynctask to trigger a get command on a local Arduino server. It appends the Arduino's pin number and, depending on if it's needed, a port number to the end of the URL. I'm sure you could use it to help you out.