display file content line by line in textview - java

I have this code below: I want to view every line by line in textview but there is a problem,
public class Resulat2 extends Activity {
private Handler h = new Handler();
private Handler mHandler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newee);
try {
File file2 = new File(Ppp.path);
FileReader fileReader = new FileReader(file2);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
final ScrollView scrollview = (ScrollView) findViewById(R.id.scrollView);
final TextView textview = (TextView) findViewById(R.id.textView10);
final StringBuilder sb = new StringBuilder("");
while ((line = bufferedReader.readLine()) != null){
final String finalLine = line;
new Thread(new Runnable() {
public void run() {
sb.append(finalLine);
sb.append("\n");
Log.d("testing5", finalLine);
}
}).start();
Thread.sleep(1000);
}
runOnUiThread(new Runnable() {
public void run() {
textview.setText(sb.toString());
textview.setMovementMethod(new ScrollingMovementMethod());
scrollview.post(new Runnable() {
#Override
public void run() {
scrollview.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
});
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
When I run, the log.d works perfectly but the textview is not shown.

your update for the textview has a minor flaw, it runs only once and then stops...
a simple solution might be introducing a boolean or (even more simply) check if your 'line' not is null...
runOnUiThread(new Runnable() {
public void run() {
while(line!= null){
textview.setText(sb.toString());
//...
Thread.sleep(200) //let other processes have some cpu
}
});
}
});
don't forget to make your String line a member of your class, so that your Runnable has access to it...
private String line = null;

Try this..it might help
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text);

Related

AndroidStudio - save user info in CSV file and read it

I'm a newbie in programming on Android Studio. I'm trying to create a simple application to gain basic experience. In the application, I would need to store individual inputs to a file (ideally CSV) in internal memory. First of all, I am trying to save user data - my name and phone number. The save method looks like this:
public void save(View view)
{
String fileName = "user.csv";
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(getFilesDir().getName(), ContextWrapper.MODE_PRIVATE);
File file = new File(directory, fileName);
String data = "FirstName,LastName,PhoneNumber";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
outputStream.write(data.getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
The data seems to be saved and I'm redirected to MainActivity. Here is the method:
protected void onCreate(Bundle savedInstanceState) {
File file = new File(getFilesDir(),"user.csv");
if(!file.exists()) {
Intent intent = new Intent(this, activity_login.class);
startActivity(intent);
}
else {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv_name = findViewById(R.id.tv_name);
TextView tv_phone = findViewById(R.id.tv_phone);
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("user.csv"));
while ((sCurrentLine = br.readLine()) != null) {
tv_name.setText(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
No value is stored in TextView tv_name and the box is empty. Where am I making mistake?
Thank you very much for your help!
For reading data saved use this method uses, UTF_8 ENCODING
public static String readAsString(InputStream is) throws IOException {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
String line;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
reader = new BufferedReader(new InputStreamReader(is,UTF_8));
}
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} finally {
if (reader != null) {
reader.close();
}
}
return sb.toString();
}
Use this method as follows, parsing file "user.csv".
public static String readFileAsString(File file) throws IOException {
return readAsString(new FileInputStream(file));
}
Fetch string and set textView
Use as this to read file:
FileInputStream fis = new FileInputStream("your full file path");
BufferedReader bfr = new BufferedReader(new InputStreamReader(fis));
Below is the code for creating .csv file and inserting data into it.
For more look into my answer :https://stackoverflow.com/a/48643905/8448886
CODE HERE:
String csv = (Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyCsvFile.csv"); // Here csv file name is MyCsvFile.csv
//by Hiting button csv will create inside phone storage.
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CSVWriter writer = null;
try {
writer = new CSVWriter(new FileWriter(csv));
List<String[]> data = new ArrayList<String[]>();
data.add(new String[]{"Country", "Capital"});
data.add(new String[]{"India", "New Delhi"});
data.add(new String[]{"United States", "Washington D.C"});
data.add(new String[]{"Germany", "Berlin"});
writer.writeAll(data); // data is adding to csv
writer.close();
callRead();
} catch (IOException e) {
e.printStackTrace();
}
}
});

JSON error loading

I am trying to save a simple name and load it – just to make everything clear to myself – there is no error, but when it loads it loads something different. It has something to do with Android itself.
Here is the class where I save and load (I don't use any libraries):
public class Serializer
{
private Context context;
private String fn;
public Serializer(Context con , String filename){
this.context = con;
this.fn = filename;
}
public void save(ArrayList<String> usernames) throws JSONException, IOException {
JSONArray JsonArray = new JSONArray();
JSONObject obj = new JSONObject();
for(String s : usernames){
obj.put("username" , s);
JsonArray.put(obj);
}
Writer writer = null;
OutputStream out = context.openFileOutput(fn , 0);
writer = new OutputStreamWriter(out);
writer.write(JsonArray.toString());
if(writer != null){
writer.close();
}
}
public ArrayList<String> load () throws IOException, JSONException {
ArrayList<String > strings = new ArrayList<>();
InputStream in = context.openFileInput(fn);
InputStreamReader reader = new InputStreamReader(in);
BufferedReader Reader = new BufferedReader(reader);
StringBuilder builder = new StringBuilder();
String Line;
while((Line = Reader.readLine() ) != null){
builder.append(Line);
}
JSONArray array = (JSONArray)new JSONTokener(builder.toString()).nextValue();
for(int i = 0 ; i < array.length() ; i++){
String jack = (String) array.getJSONObject(i).get("username");
strings.add(jack);
}
if(reader!=null){
reader.close();
}
return strings;
}
}
Here is my main activity whose layout is a simple layout with one TextEdit:
public class MainActivity extends AppCompatActivity {
Serializer serializer;
ArrayList<String> usernames;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serializer = new Serializer(this,"Jacop");
TextView txtView = findViewById(R.id.txt);
usernames = new ArrayList<>();
usernames.add(txtView.toString());
try {
ArrayList<String> username = serializer.load();
txtView.setText(username.get(0));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onResume(){
super.onResume();
try {
serializer.save(usernames);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The output (e.g what the text view shows after I close and reopen the app).
android.support.v7.widget.AppCompatEditText{73d0e9d VFED..CL. ......I. 0,0-0,0 #7f07007b app:id/txt}
You are adding an Object as String .
usernames.add(txtView.toString());
Change it to
usernames.add(txtView.getText().toString());
toString() is a method of Object class so each class have it . and android.support.v7.widget.AppCompatEditText{73d0e9d VFED..CL. ......I. 0,0-0,0 #7f07007b app:id/txt} is the string representation of the TextView object .

Android - put data into array in asynctask

I got a question that I don't know how to solve.
I am trying to achieve putting the 'question' and 'answer' into the 2D Array, but it cannot put the data into the 2D array in the asyncTask.
I am expecting I can put the 'question' and 'answer' that get in JSON Object into the 2D array. And then use the array in OnCreate method.
public class MainActivity extends Activity {
String[][] array = new String[10][4];
private TextView tvData;
int qnum = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
String quest;
String ans;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new JSONTask().execute("http://itdmoodle.hung0530.com/ptms/questions_ws.php");
Button btnNext = (Button) findViewById(R.id.btnNext);
tvData = (TextView) findViewById(R.id.textView);
for(int i=0;i<10;i++){
int z = i+1;
array[i][0] = String.valueOf(z);
}
quest = array[0][1];
ans = array[0][2];
tvData.setText(quest);
btnNext.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
}
});
}
public class JSONTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
HttpURLConnection conn = null;
BufferedReader reader = null;
try{
URL url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.connect();
InputStream stream = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while((line = reader.readLine()) != null){
buffer.append(line);
}
String Json = buffer.toString();
JSONObject jsonObject = new JSONObject(Json);
JSONArray jsonArray = jsonObject.getJSONArray("Questions");
StringBuffer bufferQues = new StringBuffer();
StringBuffer bufferAns = new StringBuffer();
for(int i=0;i<jsonArray.length();i++) {
JSONObject otherJson = jsonArray.getJSONObject(i);
String question = otherJson.getString("question");
String answer = otherJson.getString("answer");
bufferQues.append(question);
bufferAns.append(answer);
array[i][1] = bufferQues.toString();
array[i][2] = bufferAns.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally{
if(conn != null){
conn.disconnect();
}
try{
if(reader != null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
}
}
}
Asynctask executes asynchronously. It allows you to perform long running operations on a background thread(doInBackground is run on a seperate thread than main thread) and use the results to perform operations on main thread(onPostExecute runs on main thread).
What you want is to perform the operation on your 2D array in onPostExecute and not in onCreate.

OnPostExecute not getting string

The contents of the string descript is showing up in logcat with no problems but won't display on the textview in the dialog located in OnPostExecute. It's a nullpointer exception. I'm not sure why since the episode string works just fine. Can anyone tell me why?
class getDescContent extends AsyncTask<Void, Void, Void> {
FileInputStream input = null;
String episode = null;
String descript = null;
#Override
protected Void doInBackground(Void... arg0) {
try {
input = new FileInputStream(descFile);
BufferedReader br = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = br.readLine()) != null) {
if (line.length() < 50) {
episode = line;
continue;
}
descript = line;
Log.i("", descript);
}
input.close();
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.info_dialog);
dialog.setTitle(episode);
TextView descrip = (TextView) findViewById(R.id.dialog_text);
descrip.setText(descript);
dialog.show();
}
}
You should use
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.info_dialog);
dialog.setTitle(episode);
TextView descrip = (TextView) dialog.findViewById(R.id.dialog_text); //change in this line
descrip.setText(descript);
dialog.show();
Since the textview is not in the layout of the activity but in the layout of the dialog.
In your code, descrip is null, because it cannot be found.

Reading from a text file in android

I'm trying to read a random line from a file. My code doesn't have error, just comes up with a force close as soon as it runs in the emulator and I can't work out why!
public class filereader extends Activity {
TextView t = (TextView)findViewById(R.id.text);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
Scanner s = new Scanner(getResources().openRawResource(R.raw.lev1)); {
try {
while (s.hasNext()) {
String word = s.next();
t.setText(word);
}
}
finally {
s.close();
}
}
}
TextView t = (TextView)findViewById(R.id.text);
you can not run findViewById until the setContentView has been called:
TextView t = null; #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = (TextView)findViewById(R.id.text);
}
please be sure that you declare text inside the main.xml
do this
BufferedReader myReader = null;
try
{
fIn = openFileInput("customer_number.txt");
myReader = new BufferedReader(new InputStreamReader(fIn));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String aDataRow = "";
//String aBuffer = "";
try
{
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
// TO display Whole Data of File
Toast.makeText(getBaseContext(),aBuffer,Toast.LENGTH_SHORT).show();
}
// To display Last Entered Number
Toast.makeText(getBaseContext(),last_number,Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public void readfromfile(){
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
String s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
It will read the text file named "mytext.txt" string by string and store it by appending it to string variable s. So the variable "s" contains final string taken from file.

Categories

Resources