Problems with creating AsyncTask. text file in an arraylist - java

I'm having some problems creating a method that runs in the background. I'm using Android studio java and want to create a method that loads a text file in an array-list. I have tried to do this in a public method in a separate class from the activity class. When I run the application, I get problems indicating problems with main thread, so I want to make an asynctask. I have looked all over the internet, but I cannot find anything relevant. Please ask if something was unclear since I'm a beginner. Any help is appreciated!
This is from a class that will send a variable to public void CreateQuestion(), which is below the first code:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_action);
Intent callingIntent = getIntent();
int index = callingIntent.getIntExtra("INDEX",0);
if(index==0){
mQuestionBox = new QuestionBox();
try {
mQuestionBox.createQuestions("hogskoleprovet.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
else if(index==1){
mQuestionBox = new QuestionBox();
try {
mQuestionBox.createQuestions("hogskoleprovet.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
else if(index==2){
mQuestionBox = new QuestionBox();
try {
mQuestionBox.createQuestions("hogskoleprovet.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
I want to make this code as an asynctask, but I do not know how to do this.
public void createQuestions(String hogskoleprovet) throws IOException {
InputStream iS = sContext.getAssets().open(hogskoleprovet);
BufferedReader reader = new BufferedReader(new InputStreamReader(iS));
mQuestions = new ArrayList<Question>();
String question, answer, answerOne, answerTwo, answerThree, answerFour;
while (reader.readLine() != null) {
//reading some lines from resource file
question = reader.readLine();
answer = reader.readLine();
answerOne = reader.readLine();
answerTwo = reader.readLine();
answerThree = reader.readLine();
answerFour = reader.readLine();
Question q = new Question(question, answer, answerOne, answerTwo, answerThree, answerFour);
mQuestions.add(q);
break;
}
reader.close();
}

Try to modify your createQuestions method like this:
public void createQuestions(final String hogskoleprovet) throws IOException {
new AsyncTask<Integer, Integer, Boolean>()
{
#Override
protected void onPreExecute()
{
}
#Override
protected Boolean doInBackground(Integer… params)
{
InputStream iS = sContext.getAssets().open(hogskoleprovet);
BufferedReader reader = new BufferedReader(new InputStreamReader(iS));
mQuestions = new ArrayList<Question>();
String question, answer, answerOne, answerTwo, answerThree, answerFour;
while (reader.readLine() != null) {
//reading some lines from resource file
question = reader.readLine();
answer = reader.readLine();
answerOne = reader.readLine();
answerTwo = reader.readLine();
answerThree = reader.readLine();
answerFour = reader.readLine();
Question q = new Question(question, answer, answerOne, answerTwo, answerThree, answerFour);
mQuestions.add(q);
break;
}
reader.close();
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
}
}.execute();
}

Asynctask class to read the data from file
public class FileReader_async extends AsyncTask{
private Context context;
private Callback callback;
private List<Question> mQuestions;
public FileReader_async(Context context,Callback callback)
{
this.callback=callback;
}
#Override
protected Object doInBackground(Object... params) {
InputStream iS = null;
try {
iS = context.getAssets().open("filename");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(iS));
mQuestions = new ArrayList<Question>();
String question, answer, answerOne, answerTwo, answerThree, answerFour;
try {
while (reader.readLine() != null) {
//reading some lines from resource file
question = reader.readLine();
answer = reader.readLine();
answerOne = reader.readLine();
answerTwo = reader.readLine();
answerThree = reader.readLine();
answerFour = reader.readLine();
Question q = new Question(question, answer, answerOne, answerTwo, answerThree, answerFour);
mQuestions.add(q);
break;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
#Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
callback.notify_result(mQuestions);
}
}
callback interface to notify when the asnyctask is finished
public interface Callback {
public void notify_result(List<Question> question_list);
}
activity invoking the asynctask to read the data from file..
public class MainActivity extends ActionBarActivity implements Callback{
private FileReader_async fileReader_async;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//invoke the asynctask when you want to read the question.. to invoke asynctask code
fileReader_async=new FileReader_async(getApplicationContext(), this);
fileReader_async.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void notify_result(List<Question> question_list) {
//you can use the question_list from here
}
}

Related

JSON ListView filter not working

So I've got a project to make a simple job board app. I've retrieved my JSON data and have it displaying on my app but I want to be able to use a SearchView filter but I don't know how to access my SimpleAdapter from outside of an inner-class
Here is my code:
public class jobcategories extends Activity{
private TextView jobData;
private ProgressDialog myprocessingdialog;
ArrayAdapter<String> adapter;
ArrayList<HashMap<String, String>> jobList;
private ListView lv;
private SearchView sv;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jobcategories);
myprocessingdialog = new ProgressDialog(this);
jobList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
sv = (SearchView) findViewById(R.id.search);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
new JSONTask().execute("https://apidata.com");
}
public class JSONTask extends AsyncTask<String,String, String>{
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//Showing Progress dialogue
myprocessingdialog.setTitle("Please Wait..");
myprocessingdialog.setMessage("Loading");
myprocessingdialog.setCancelable(false);
myprocessingdialog.setIndeterminate(false);
myprocessingdialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try{
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentObject = new JSONArray(finalJson);
for (int i=0; i < parentObject.length(); i++) {
JSONObject job = parentObject.getJSONObject(i);
String JobTitle = job.getString("title");
String JobLocation = job.getString("location");
String finalTitle = JobTitle + " in " + JobLocation;
String JobCompany = "advert by "+job.getString("company");
String JobDescription = job.getString("description");
String JobApply = "How to Apply: " + job.getString("apply");
HashMap<String, String> jobs = new HashMap<>();
jobs.put("title", finalTitle);
jobs.put("company", JobCompany);
jobs.put("description", JobDescription);
jobs.put("apply", JobApply);
jobList.add(jobs);
}
}catch (MalformedURLException e){
Toast.makeText(getApplicationContext(), "Error...the job server is down..." + e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "error parsing..." + e.toString(), Toast.LENGTH_LONG).show();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String results) {
super.onPostExecute(results);
myprocessingdialog.cancel();
ListAdapter adapter = new SimpleAdapter(
jobcategories.this, jobList,
R.layout.list_item, new String[]{"title", "company", "description", "apply"},
new int[]{R.id.title, R.id.company, R.id.description, R.id.apply});
lv.setAdapter(adapter);
}
}
}
Any help would be appreciated, am pretty new to android so if there is a better way for me to filter the data then I am open to changing the code.
Create an interface called OnJsonResultListener like so:
public interface OnJsonResultListener {
void onResult(String result);
}
Then make your Activity/Fragment implement that interface and do whatever with your simple adapter and the result from there. Then make the AsyncTask take a OnJsonResultListener in the constructor. Then in the onPostExecute method, call listener.onResult(results);
This is a simple way of making a callback.

InputStream does not want to read from a textfile android studio

I have problems with android programming in java, because it does not want to read from a text file. The problem is that the buttons do not add the text which I am trying to do in the async-class. Furthermore, the buttons which will show the text does not work, because when I press on a button the application stops working.
Short introduction of the program:
The application starts with a value sent to gameAction from a spinner, and from there it wil invoke a name on text-file which will be loaded into strings in an array-list, the class QuestionBox. Lastly it will questions will be made in GameAction class.
If something was unclear, please comment. And any help is appreciated! Excuse me for adding a lot of code, but I added it due to not knowing how to do.
public class QuestionBox extends AsyncTask<Object, Void, Object>{
private Context context;
private Callback callback;
private List<Question> mQuestions;
public QuestionBox(Context context,Callback callback)
{
mQuestions = new ArrayList<Question>();
this.callback=callback;
this.context= context;
}
public Callback getCallback(){
return callback;
}
#Override
protected Object doInBackground(Object... params) {
InputStream iS = null;
try {
iS = context.getAssets().open("hogskoleprovet.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println("Hit kom du");
BufferedReader reader = new BufferedReader(new InputStreamReader(iS));
String question, answer, answerOne, answerTwo, answerThree, answerFour;
try {
while (reader.readLine() != null) {
//reading some lines from resource file
question = reader.readLine();
answer = reader.readLine();
answerOne = reader.readLine();
answerTwo = reader.readLine();
answerThree = reader.readLine();
answerFour = reader.readLine();
Question q = new Question(question, answer, answerOne, answerTwo, answerThree, answerFour);
mQuestions.add(q);
break;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
reader.close();
System.out.println("Hit kom du3");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
public interface Callback{
public void notify_result(List<Question> question_list);
}
#Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
public int getQuestionsLeft() {
return mQuestions.size();
}
public Question getRandomQuestion() {
Random random = new Random();
int index = random.nextInt(mQuestions.size());
Question newQuestion = mQuestions.get(index);
mQuestions.remove(index);
return newQuestion;
}
}
Here is another method which the strings will be sent to:
public class gameAction extends ActionBarActivity implements QuestionBox.Callback{
private QuestionBox mQuestionBox;
private Question mCurrentQuestion;
private Context context;
private Callback callback;
#Override
public void notify_result(List<Question> question_list) {
}
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_action);
//Kod som kollar vad som skickades med när aktiviteten startades
Intent callingIntent = getIntent();
int index = callingIntent.getIntExtra("INDEX",0);
//Bestäm filnamn beroende på vad som skickades med
if(index==0){
mQuestionBox =new QuestionBox(getApplicationContext(), this);
mQuestionBox.execute("hogskoleprovet.txt");
}
else {
if (index == 1 ) {
mQuestionBox =new QuestionBox(getApplicationContext(), this);
mQuestionBox.execute("hogskoleprovet.txt");
} else if (index == 1) {
mQuestionBox =new QuestionBox(getApplicationContext(), this);
mQuestionBox.execute("hogskoleprovet.txt");
} else if (index == 2) {
mQuestionBox =new QuestionBox(getApplicationContext(), this);
mQuestionBox.execute("hogskoleprovet.txt");
}
}
}
public void setNewQuestion()
{
//Hämta en slumpmässig fråga från vår QuestionBox
//och lagra den i mCurrentQuestion
mCurrentQuestion = mQuestionBox.getRandomQuestion();
//Se till så att textfält och knappar visar den aktuella
//frågan
TextView questionTextView = (TextView) findViewById(R.id.questionTextView);
questionTextView.setText(mCurrentQuestion.getQuestion());
Button buttonOne = (Button) findViewById(R.id.buttonOne);
buttonOne.setText(mCurrentQuestion.getOptionOne());
Button buttonTwo = (Button) findViewById(R.id.buttonTwo);
buttonTwo.setText(mCurrentQuestion.getOptionTwo());
Button buttonThree = (Button) findViewById(R.id.buttonThree);
buttonThree.setText(mCurrentQuestion.getOptionThree());
Button buttonFour = (Button) findViewById(R.id.buttonFour);
buttonFour.setText(mCurrentQuestion.getOptionFour());
Button buttonNew = (Button) findViewById(R.id.buttonNew);
buttonOne.setEnabled(true);
buttonTwo.setEnabled(true);
buttonThree.setEnabled(true);
buttonFour.setEnabled(true);
buttonNew.setVisibility(View.INVISIBLE);
buttonOne.setText(mCurrentQuestion.getOptionOne());
buttonTwo.setText(mCurrentQuestion.getOptionTwo());
buttonThree.setText(mCurrentQuestion.getOptionThree());
buttonFour.setText(mCurrentQuestion.getOptionFour());
}
public void quitTheGame(View v){
Intent intent = new Intent (this, MainActivity.class);
Button butttonQuit = (Button) findViewById(R.id.buttonFive);
startActivity(intent);
}
public void answerClick(View V)
{
Button answerButton = (Button)V;
Button buttonOne = (Button) findViewById(R.id.buttonOne);
buttonOne.setText(mCurrentQuestion.getOptionOne());
Button buttonTwo = (Button) findViewById(R.id.buttonTwo);
buttonTwo.setText(mCurrentQuestion.getOptionTwo());
Button buttonThree = (Button) findViewById(R.id.buttonThree);
buttonThree.setText(mCurrentQuestion.getOptionThree());
Button buttonFour = (Button) findViewById(R.id.buttonFour);
buttonFour.setText(mCurrentQuestion.getOptionFour());
Button buttonNew = (Button) findViewById(R.id.buttonNew);
buttonOne.setEnabled(false);
buttonTwo.setEnabled(false);
buttonThree.setEnabled(false);
buttonFour.setEnabled(false);
buttonNew.setVisibility(View.VISIBLE);
}
public void newClick(View v){
if(mQuestionBox.getQuestionsLeft()>0){
setNewQuestion();
}
else
{
Context context = getApplicationContext();
String text = "Slut på frågor!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is the class for putting answer to correct options:
package com.example.arnpet.ultimatehogskoleprovet;
public class Question {
private String question;//Lagrar frågan
private String optionOne; //Lagrar svarsalternativ
private String optionTwo;
private String optionThree;
private String optionFour;
private String correctAnswer; //Lagrar det korrekta svaret
//konstruktor
public Question (String question, String optionOne, String optionTwo,
String optionThree, String optionFour, String correctAnswer)
{
this.question = question;
this.optionOne = optionOne;
this.optionTwo = optionTwo;
this.optionThree = optionThree;
this.optionFour = optionFour;
}
public String getQuestion() {
return question;
}
public String getOptionOne() {
return optionOne;
}
public String getOptionTwo() {
return optionTwo;
}
public String getOptionThree() {
return optionThree;
}
public String getOptionFour() {
return optionFour;
}
}
while (reader.readLine() != null)
Here you are reading a line of the file and throwing it away. Not what you want, unless your file is strangely structured with ignorable junk lines every so often.
The usual loop looks like this:
while ((line = reader.readLine()) != null)
and then using line in the controlled block.
Secondly, this is the only place you check for null, yet you have several other readLine() calls, any one of which can return null. So you run some risk of NPEs later in your code.

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.

onItemClick not working when clicked

I am missing something very crucial but I can't quite see what. Can someone please assist. It's probably something really silly that I have missed but I cannot initiate my onItemClick.
onCreate....
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
actu_ip = intent.getStringExtra(IPEntry.ACTUALSMARTIP);
setContentView(R.layout.act_ipcontrol);
mainListView = (ListView) findViewById( R.id.mainListView );
String[] options = new String[] { "All in to 1", "Spare"};
ArrayList<String> optionsList = new ArrayList<String>();
optionsList.addAll( Arrays.asList(options) );
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, optionsList);
mainListView.setAdapter( listAdapter );
try {
Toast.makeText(IPControl.this, "Please wait...Connecting...", Toast.LENGTH_SHORT).show();
new AsyncAction().execute();
} catch(Exception e) {
e.printStackTrace();
}
}
private class AsyncAction extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
try {
InetAddress serverAddr = InetAddress.getByName(actu_ip);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
out = new PrintWriter(bw, true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (! in .ready());
readBuffer();
out.println("root\r\n");
while (! in .ready());
readBuffer();
out.println("root\r\n");
while (! in .ready());
readBuffer();
out.println("[verbose,off\r\n");
while (! in .ready());
String msg = "";
while ( in .ready()) {
msg = msg + (char) in .read();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;//returns what you want to pass to the onPostExecute()
}
protected void onPostExecute(String result) {
Toast.makeText(IPControl.this, "Connected", Toast.LENGTH_SHORT).show();
//results the data returned from doInbackground
IPControl.this.data = result;
}
}
private String readBuffer() throws IOException {
String msg = "";
while(in.ready()) {
msg = msg + (char)in.read();
}
//System.out.print(msg);
if(msg.indexOf("SNX_COM> ") != -1) return msg.substring(0, msg.indexOf("SNX_COM> "));
else if(msg.indexOf("SCX_COM> ") != -1) return msg.substring(0, msg.indexOf("SCX_COM> "));
else return msg;
}
}
What I want to initiate...
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
try {
new AsyncAction1().execute();
} catch(Exception e) {
e.printStackTrace();
}
}
private class AsyncAction1 extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
try {
out.println("[c,l#,i1,o*\r\n");
//System.out.print("root\r\n");
while(! in .ready());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;//returns what you want to pass to the onPostExecute()
}
protected void onPostExecute(String result) {
//results the data returned from doInbackground
Toast.makeText(IPControl.this, "Command Sent", Toast.LENGTH_SHORT).show();
IPControl.this.data = result;
}
}
I haven't seen setOnItemClickListener method for listview in your code. Have you implemented it?
Try following
mainListView.setAdapter( listAdapter );
mainListView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
try {
new AsyncAction1().execute();
}catch(Exception e) {
e.printStackTrace();
}
});
Thanks for all your help, I fixed my problem.
I just wasn't doing things in the correct order.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
actu_ip = intent.getStringExtra(IPEntry.ACTUALSMARTIP);
setContentView(R.layout.act_ipcontrol);
mainListView = (ListView) findViewById( R.id.mainListView );
final String[] options = new String[] { "All in to 1", "Spare"};
ArrayList<String> optionsList = new ArrayList<String>();
optionsList.addAll( Arrays.asList(options) );
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, optionsList);
mainListView.setAdapter( listAdapter );
mainListView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
try {
if(pos == 0) {
AsyncAction1 a = new AsyncAction1();
a.setCmd("[c,l#,i1,o*\r\n");
a.execute();
}
} catch(Exception e) {
e.printStackTrace();
}
}
});
Then....
private class AsyncAction1 extends AsyncTask<String, Void, String> {
String cmd;
public void setCmd(String c) {
cmd = c;
}
protected String doInBackground(String... args) {
try {
out.println(cmd);
//System.out.print("root\r\n");
while(! in .ready());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;//returns what you want to pass to the onPostExecute()
}
protected void onPostExecute(String result) {
//results the data returned from doInbackground
Toast.makeText(IPControl.this, "Command Sent", Toast.LENGTH_SHORT).show();
IPControl.this.data = result;
}
}
}

Convert Text File to String in java

i have a written a code to send a text file by converting it into string and sending it into a web service. Please can someone tell me other available methods for sending the string as stream to Web Service.
public class MainActivity extends Activity {
Button b1;
String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
File upfile=new File("sdcard/text/testfile.txt");
try {
FileInputStream fin=new FileInputStream(upfile);
byte[] buffer= new byte[(int)upfile.length()];
new DataInputStream(fin).readFully(buffer);
fin.close();
s=new String(buffer,"UTF-8");
System.out.print(buffer);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, s, 20).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
try this.
public void mReadJsonData() {
try {
File f = new File("sdcard/text/testfile.txt");
FileInputStream is = new FileInputStream(f);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String text = new String(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Use this code to read the data from file and get it into string and do your process ahead according to your need--
File upfile=new File("sdcard/text/testfile.txt");
try {
final BufferedReader reader = new BufferedReader(new FileReader(upfile));
String encoded = "";
try {
String line;
while ((line = reader.readLine()) != null) {
encoded += line;
}
}
finally {
reader.close();
}
System.out.print(encoded);
}
catch (final Exception e) {
}

Categories

Resources