File reading not working for android - android

I am an android newbie and wrote this code for file handling but for some reason i am always getting back null values from the file. I also tried using readline() but got the same result. Would appreciate any help.
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
String file = "test123";
try
{
OutputStream out = v.getContext().openFileOutput(file, MODE_PRIVATE);
InputStream in = v.getContext().openFileInput(file);
WriteFile(out);
String str = ReadFile(in);
Toast.makeText(v.getContext(), str, Toast.LENGTH_LONG);
} catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public static void WriteFile(OutputStream out)
{
OutputStreamWriter tmp = new OutputStreamWriter(out);
try
{
for (int i = 0 ; i < 10; i++)
{
tmp.write(i);
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String ReadFile(InputStream in)
{
InputStreamReader tmp = null;
String str = "";
tmp = new InputStreamReader(in);
BufferedReader reader=new BufferedReader(tmp);
try
{
for (int i = 0; i < 10; i++)
{
str += " " + reader.readLine();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
}

String file = "test123";
So, the path of your file should be {root}/test123
Try defining a path were you can access to see if it has written something. (usually : /mnt/storage/your_file)
Then, you'll be able to determine if the Write/Read process works or not
Note : Take a look at FileOutputStream, it already implements lots of useful methods

Related

OpenCSV read specific column

i am facing small problem while using OPENCSV and trying to read specific column from a line. I have a csv file that looks like this
"ID","Name","Name2","Date","Author"
"1","Alex","Example","18.3.2016","Alex"
Now i want to read only the column 2 and 3 (Name and Name2).
My code looks like this
try {
CSVReader reader = new CSVReader(new FileReader(filelocation));
String [] nextLine;
int rowNumber = 0;
while ((nextLine = reader.readNext()) != null) {
rowNumber++;
for(int i = 0; i< nextLine.length ; i++){
System.out.println("Cell index: " + i);
System.out.println("Cell Value: " + nextLine[i]);
System.out.println("---");
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I already tried setting the "i" variable manually to 1 and 2. But then i am getting 4 same results shown in log. What is missing? Thanks!
Never mind, i found the trick.
Here is how it should look.
try {
CSVReader reader = new CSVReader(new FileReader(filelocation));
String [] nextLine;
int rowNumber = 0;
while ((nextLine = reader.readNext()) != null) {
rowNumber++;
String name = nextLine[1];
String name2 = nextLine[2];
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
After it, i could get the string value and work with it.

clearing multiple apps' data android

I'm able to clear a single package name's data through this snippet. However, i want it to handle more than one package names. in other words, it should clear two more package names' data
private void clearData() {
//"com.uc.browser.en"
//"pm clear com.sec.android.app.sbrowser"
String cmd = "pm clear com.sec.android.app.sbrowser" ;
ProcessBuilder pb = new ProcessBuilder().redirectErrorStream(true)
.command("su");
Process p = null;
try {
p = pb.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// We must handle the result stream in another Thread first
StreamReader stdoutReader = new StreamReader(p.getInputStream(),
CHARSET_NAME);
stdoutReader.start();
out = p.getOutputStream();
try {
out.write((cmd + "\n").getBytes(CHARSET_NAME));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
out.write(("exit" + "\n").getBytes(CHARSET_NAME));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
p.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String result = stdoutReader.getResult();
}
}
The ProcessCommandsSU class starts an su process in which to run a list of commands, and provides an interface to deliver the output to an Activity asynchronously. Unlike the example you're following, this class will not block the UI thread. The Activity must implement the OnCommandsReturnListener interface.
public class ProcessCommandsSU extends Thread {
public interface OnCommandsReturnListener {
public void onCommandsReturn(String output);
}
private final Activity activity;
private final String[] cmds;
public ProcessCommandsSU(Activity activity, String[] cmds) {
if(!(activity instanceof OnCommandsReturnListener)) {
throw new IllegalArgumentException(
"Activity must implement OnCommandsReturnListener interface");
}
this.activity = activity;
this.cmds = cmds;
}
public void run() {
try {
final Process process = new ProcessBuilder()
.redirectErrorStream(true)
.command("su")
.start();
final OutputStream os = process.getOutputStream();
final CountDownLatch latch = new CountDownLatch(1);
final OutputReader or = new OutputReader(process.getInputStream(), latch);
or.start();
for (int i = 0; i < cmds.length; i++) {
os.write((cmds[i] + "\n").getBytes());
}
os.write(("exit\n").getBytes());
os.flush();
process.waitFor();
latch.await();
process.destroy();
final String output = or.getOutput();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
((OnCommandsReturnListener) activity).onCommandsReturn(output);
}
}
);
}
catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
private class OutputReader extends Thread {
private final InputStream is;
private final StringBuilder sb = new StringBuilder();
private final CountDownLatch latch;
public OutputReader(InputStream is, CountDownLatch latch) {
this.is = is;
this.latch = latch;
}
public String getOutput() {
return sb.toString();
}
public void run() {
try {
final BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e) {
e.printStackTrace();
}
latch.countDown();
}
}
}
Using the class is quite simple. We first ensure that our Activity implements the interface. We then create an instance, passing the Activity and our array of commands in the constructor, and call its start() method. In the following example, it's assumed that the Activity has a TextView named textOutput to display the returned output:
public class MainActivity extends Activity
implements ProcessCommandsSU.OnCommandsReturnListener {
...
#Override
public void onCommandsReturn(String output) {
textOutput.append(output + "\n");
}
private void runCommands() {
final String[] cmds = {
"ping -c 5 www.google.com",
"pm list packages android",
"chdir " + Environment.getExternalStorageDirectory(),
"ls"
};
new ProcessCommandsSU(MainActivity.this, cmds).start();
}
}
My device is not rooted, so this was tested with the commands you see in the code above. Simply replace those commands with your pm clear commands.

android, Read content of 100-300 files from FTP folder... Hangs

I am using RetrieveFilestream method with BufferedInputStream in a for loop. I am closing all
streams after processing each file and also adding ftp complete pending command.
Every thing works as expected in my test environment with few files. But in realtime data where there are 200-300 files, it hangs somewhere.
It is not throwing any exception making it difficult to debug. Cannot debug one by one. Any help?
Here is my code Block.
public String LoopThroughFiles(FTPClient myftp, String DirectoryName)
{
boolean flag=false;
String output="";
InputStream inStream=null;
BufferedInputStream bInf= null;
StringBuilder mystring = new StringBuilder();
progressBar = (ProgressBar) findViewById(R.id.progressBar);
try {
flag= myftp.changeWorkingDirectory(DirectoryName);
if(flag==true)
{
FTPFile[] files = myftp.listFiles();
progressBar.setMax(files.length);
String fname="";
myftp.enterLocalPassiveMode();
if(files.length > 0)
{
int n=0;
for (FTPFile file : files)
{
n=n+1;
int r= progressBar.getProgress();
progressBar.setProgress(r+n);
fname=file.getName();
// String path= myftp.printWorkingDirectory();
if(fname.indexOf("txt") != -1)
{
inStream = myftp.retrieveFileStream(fname);
int reply = myftp.getReplyCode();
if (inStream == null || (!FTPReply.isPositivePreliminary(reply) && !FTPReply.isPositiveCompletion(reply))) {Log.e("error retrieving file",myftp.getReplyString()); }
bInf=new BufferedInputStream (inStream);
int bytesRead;
byte[] buffer=new byte[1024];
String fileContent=null;
while((bytesRead=bInf.read(buffer))!=-1)
{
fileContent=new String(buffer,0,bytesRead);
mystring.append(fileContent);
}
mystring.append(",");
bInf.close();
inStream.close();
boolean isSucess= myftp.completePendingCommand();
if(isSucess == false)
Log.e("error retrieving file","Failed to retrieve the stream for " + fname);
}
}
flag= myftp.changeToParentDirectory();
}
}
}
catch (java.net.UnknownHostException e) {
e.printStackTrace();
Log.e("readfile,UnknownHost",e.getMessage());
}
catch (java.io.IOException e) {
e.printStackTrace();
Log.e("readfile,IO",e.getMessage());
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("readfile,General",e.getMessage());
}
finally
{
try {
output = mystring.toString();
if(bInf != null)
bInf.close();
if(inStream != null)
inStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("readfile,finallyblock",e.getMessage());
}
}
return output;
}

parsing from String to Float returns float value with question marks in it

So as the title says i am trying to parse a string value into a float value but i am getting a number format exception like this Invalid float: "3??.??5??2" the actual number is 3.52. Oh and im doing it all in a Fragment which causes me troubles. Im also not using any DecimalFormats on this Float value when im saving it to a file. So what am i doing wrong? :(
The way i am reading/writing a file is this:
file = new File(Environment
.getExternalStorageDirectory()
+ File.separator
+ "userZinsenArray.txt");
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String outputString = "";
try {
if (!file.exists())
file.createNewFile();
System.out.println("file exists:" + file.exists());
FileOutputStream stream = new FileOutputStream(file);
DataOutputStream ps = new DataOutputStream(stream);
for (int i = 0; i < MainActivity.prozentenArray.size(); i++) {
outputString+=(""+MainActivity.prozentenArray.get(i));
outputString+="\n";
}
ps.writeChars(outputString);
ps.close();
stream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
load.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String line=null;
try {
InputStream in = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(in);
BufferedReader buffreader = new BufferedReader(input);
while (( line = buffreader.readLine()) != null) {
MainActivity.prozentenArray.add(Float.parseFloat(line));
}
in.close();
} catch(NumberFormatException e){
System.out.println("numberFormatException: "+e.getMessage());
}catch(Exception e){
System.out.println("other exp: "+e.getMessage());
}
}
});
try this:
InputStreamReader input = new InputStreamReader(in, "UTF-8");

Button text and string from text file (from asset) should be the same, but not in Android

I would like to make a quiz program. The questions are in a text file in asset folder. The answers are also in the asset folder called the number of the question (for example: the first question answers are in the text file called 1). I would like to give the questions and answers randomly (answers to a button). Until this everything is all right (maybe not the shortest solution, but works well). Then the user can answer the question clicking the correct button. And here is the problem. I get the text of the button and the first row of the answer file (always the first row is the right answer in the answer text file). It should be the same, and then I sign, this is the correct answer. But it's not the same, and I don't know why. A put text to the button from the answer file and get the first row from the answer file, so it should be the same. I print it out to log cat, and look like they are the same. I don't know what could be went wrong.
Can anybody help me out.
This is where I set the text of the button (randomly) and compare the first rows and the text of the button:
BufferedReader br2 = new BufferedReader(is2, 8192);
for(int k2=0; k2<3; k2++){
try {
kerdes2[k2] = br2.readLine();
final ArrayList <Integer> kerdesno2 = new ArrayList<Integer>();
for(int j=0;j<3;j++) kerdesno2.add(j);
Collections.shuffle(kerdesno2);
System.out.println(kerdesno2);
answ.setText(kerdes2[kerdesno2.get(0)]);
answ2.setText(kerdes2[kerdesno2.get(1)]);
answ3.setText(kerdes2[kerdesno2.get(2)]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
answ.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
InputStreamReader is3 = null;
try {
is3 = new InputStreamReader(am.open(i3), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br3 = new BufferedReader(is3, 8192);
try {
String helyes = br3.readLine();
System.out.println(helyes);
String gomb = answ.getText().toString();
System.out.println(gomb);
for(int f=0; f<helyes.length(); f++)
{
char c = helyes.charAt(f);
char d = gomb.charAt(f);
if(c != d){
System.out.println(c);
System.out.println(((String) gomb).indexOf(c));
}
}
if(gomb == helyes)
{
x++;
TextView eredmeny = (TextView)findViewById(R.id.eredmeny);
eredmeny.setText("Eredményed: " + Math.round(x*100/i2) + "%");
}
else
{
TextView eredmeny = (TextView)findViewById(R.id.eredmeny);
eredmeny.setText(gomb + " = " + helyes);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
answ2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
InputStreamReader is3 = null;
try {
is3 = new InputStreamReader(am.open(i3), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br3 = new BufferedReader(is3, 8192);
try {
String helyes = br3.readLine();
System.out.println(helyes);
String gomb = answ2.getText().toString();
System.out.println(gomb);
if(gomb == helyes)
{
x++;
TextView eredmeny = (TextView)findViewById(R.id.eredmeny);
eredmeny.setText("Eredményed: " + Math.round(x*100/i2) + "%");
}
else
{
TextView eredmeny = (TextView)findViewById(R.id.eredmeny);
eredmeny.setText(gomb + " = " + helyes);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
answ3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
InputStreamReader is3 = null;
try {
is3 = new InputStreamReader(am.open(i3), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br3 = new BufferedReader(is3, 8192);
try {
String gomb = answ3.getText().toString();
String helyes = br3.readLine();
System.out.println(gomb);
System.out.println(helyes);
if(gomb == helyes){
x++;
TextView eredmeny = (TextView)findViewById(R.id.eredmeny);
eredmeny.setText("Eredményed: " + Math.round(x*100/i2) + "%");
}
else
{
TextView eredmeny = (TextView)findViewById(R.id.eredmeny);
eredmeny.setText(gomb + " = " + helyes);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
As You can see I try to iterate over the two strings to realize where the problem is, but I couldn't manage to find...
String is an object. When comparing objects, use .equals(), not ==.
Your code:
if(gomb == helyes)
Should be:
if(gomb.equals(helyes))
By using == you're comparing memory, not the actual String objects. Sometimes you'll get the expected result, but other times you won't. .equals() will always test the Strings themselves.
I can see you are comparing by
if(gomb == helyes){
while it should be
if(gomb.equals(helyes)){

Categories

Resources