ArrayList size 0 after deserialisation Android Studio Java - java

Hello I tried to make an app for displaying quote in Android Studio.
But I got stuck when reading.
I created an "ArrayList" with my custom class Quotes.
I seems to work ok when writing the ArrayList to the file, but when reading from it the size of ArrayList is 0.
public class SaveQuote extends AppCompatActivity {
EditText editTextQuote;
EditText editTextAuthor;
Button btnSave;
ArrayList<Quote> arrQuo = new ArrayList<>();
public static ArrayList<Quote> arrayListQuotesSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save_quote);
init();
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quote = editTextQuote.getText().toString();
String author =editTextAuthor.getText().toString();
addQuote(quote,author);
}
});
}
private void init(){
editTextQuote = findViewById(R.id.editTextQuote);
editTextAuthor = findViewById(R.id.editTextAuthor);
btnSave = findViewById(R.id.buttonSave);
arrayListQuotesSave = new ArrayList<>();
}
private void addQuote(String quote, String author){
Quote q = new Quote(quote, author);
arrQuo.add(q);
String path = this.getFilesDir().toString();
try {
FileOutputStream fos = openFileOutput("Quotes.txt",MODE_APPEND);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrQuo);// when I write size = 1
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis = openFileInput("Quotes.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
arrQuo =(ArrayList<Quote>) ois.readObject();
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

I tried to passe a context and call the method openFileOutput on the context
so like this:
enter code here
FileOutputStream fs = context.openFileOutput("Quotes.txt", Context.MODE_PRIVATE);
enter code here
public class SaveQuote extends AppCompatActivity {
EditText editTextQuote;
EditText editTextAuthor;
Button btnSave;
ArrayList<Quote> arrQuo = new ArrayList<>();
public static ArrayList<Quote> arrayListQuotesSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save_quote);
init();
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quote = editTextQuote.getText().toString();
String author =editTextAuthor.getText().toString();
if(quote.isEmpty() || author.isEmpty()){
Toast.makeText(SaveQuote.this,"Fill all fields",Toast.LENGTH_SHORT).show();
}else {
writeToFile(SaveQuote.this, quote, author);
Toast.makeText(SaveQuote.this,"The quote was saved",Toast.LENGTH_SHORT).show();
}
}
});
}
private void init(){
editTextQuote = findViewById(R.id.editTextQuote);
editTextAuthor = findViewById(R.id.editTextAuthor);
btnSave = findViewById(R.id.buttonSave);
arrayListQuotesSave = new ArrayList<>();
}
private void writeToFile(Context context,String quote,String author) {
Quote q = new Quote(quote,author);
MainActivity.arrayListQuotesMain.add(q);
Integer size = MainActivity.arrayListQuotesMain.size();
Log.v("Added","arrayListQuotesMain size is = "+size.toString());
try {
FileOutputStream fs = context.openFileOutput("Quotes.txt", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fs);
oos.writeObject(MainActivity.arrayListQuotesMain);
oos.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
editTextQuote.setText("");
editTextAuthor.setText("");
}
}

Related

How to play Audio from internal storage with encoded string file

I want to play a decoded string to audio file.
The string is received from another activity, but mediaPlayer shows null. How can I get and set the path in media.create()?
public class AAudio extends AppCompatActivity {
Button play_audio;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aaudio);
String recieve_file = getIntent().getStringExtra("audio_file");
play_audio = findViewById(R.id.textShow);
byte[] decoded = Base64.decode(recieve_file, 0);
String fileName = String.valueOf(decoded);
Log.e("~~~~~~~~ Decoded: ", Arrays.toString(decoded));
try {
String root = Environment.getExternalStorageDirectory().getPath();
File myDir = new File(root, "/kaushlya/mp3");
String path = String.valueOf(myDir);
myDir.mkdirs();
String audioName = "Advicory.mp3";
File file = new File(myDir, audioName);
FileOutputStream os = null;
try {
os = new FileOutputStream(file, true);
os.write(decoded);
os.close();
**mediaPlayer = MediaPlayer.create(this, Uri.parse(Uri.parse(root)+path+fileName));
mediaPlayer.setLooping(true);**
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
play_audio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.start();
}
});
}
}

How do I encrypt and Decrypt Txt file to/from external storage Android?

I know how to Write and Read data from External Storage, I don't know How to encrypt and decrypt this data to my external storage, so that whoever is trying to access that file using file explorer, It should be encrypted.
Here I have written the for storing and reading the data, for which I am using the buttons.
public class SOSActivity extends AppCompatActivity {
public EditText contact1;
Button saveButton, readButton;
private Context context;
public SharedPreferences.Editor editorcache;
private String filename = "SampleFile.txt";
private String filepath = "MyFileStorage";
File myExternalFile;
String myData = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sos);
context = this.getApplicationContext();
saveButton = (Button) findViewById(R.id.save);
contact1 = ((EditText) findViewById(R.id.contact1));
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(contact1.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
// response.setText("SampleFile.txt saved to External
// Storage...");
finish();
}
});
readButton = (Button) findViewById(R.id.read);
readButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
contact1.setText("");
try {
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
contact1.setText(myData);
// response.setText("SampleFile.txt data retrieved from Internal
// Storage...");
}
});
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
saveButton.setEnabled(false);
} else {
myExternalFile = new File(getExternalFilesDir(filepath), filename);
}
}
private static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
private static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
}
Follow the link to explore 2-way encryption.
https://stackoverflow.com/a/40175319/2761151
Warning: This method may not work for Android N

Open file in TextView from txt file created in separate activity

I have a Calendar activity. When the user selects a date, I would like the TextView under the calendar to display all events the user has stored for that date. Under the TextView is a button that takes the user to the activity where they create the event. The button on the Event Creation Activity uses fileOutputStream to save a txt file containing entered information. My issue is reading that info into the TextView on the Calendar Activity. I have the code written for the read, but when I try to point it to the directory created by the fileOutput on EventCreateActivity, I get an error "EventCreateActivity is not an enclosing class." I believe it is an enclosing class, as it has nested classes, correct? What can I do here that requires the least amount of restructuring?
Here is my CalendarActivity:
public class CalendarActivity extends AppCompatActivity {
CalendarView calendar;
Button createEvent;
public static String createEventDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
calendar = (CalendarView)findViewById(R.id.calendar);
calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener(){
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth){
createEventDate = (month+"."+dayOfMonth+"."+year);
createEvent.setText("Create Event for "+createEventDate);
File directory = EventCreateActivity.this.getFilesDir().getAbsoluteFile();
File[] dateFile = directory.listFiles();
if (dateFile.length > 0){
fillEventList();
}else{
noEventToday();
}
}
});
createEvent = (Button)findViewById(R.id.eventCreateButton);
createEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent toEventCreateActivity = new Intent(CalendarActivity.this, EventCreateActivity.class);
startActivity(toEventCreateActivity);
}
});
}
public void fillEventList (){
TextView eventList = (TextView)findViewById(R.id.eventList);
try {
String message = createEventDate;
FileInputStream fileInput = openFileInput(message);
InputStreamReader inputStreamReader = new InputStreamReader(fileInput);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
while ((message = bufferedReader.readLine())!=null){
stringBuffer.append(message+"/n");
}
eventList.setText(stringBuffer.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void noEventToday(){
TextView eventList = (TextView)findViewById(R.id.eventList);
eventList.setText("Nothing scheduled for today.");
}
}
here is my EventCreateActivity:
public class EventCreateActivity extends AppCompatActivity {
String textViewText = CalendarActivity.createEventDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_create);
TextView titleTextView = (TextView)findViewById(R.id.titleTextView);
titleTextView.setText("Create event for "+textViewText);
Button createEventButton = (Button)findViewById(R.id.saveEvent);
createEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonSaves();
Intent toCalendarActivity = new Intent(EventCreateActivity.this, CalendarActivity.class);
EventCreateActivity.this.startActivity(toCalendarActivity);
}
});
}
public void buttonSaves () {
TimePicker timePicker = (TimePicker)findViewById(R.id.timePicker);
EditText entryEvent = (EditText)findViewById(R.id.entryEvent);
EditText entryLocation = (EditText)findViewById(R.id.entryLocation);
EditText entryCrew = (EditText)findViewById(R.id.entryCrew);
final String timeHour = timePicker.getCurrentHour().toString();
final String timeMinute = timePicker.getCurrentMinute().toString();;
final String event = entryEvent.getText().toString();
final String location = entryLocation.getText().toString();
final String crew = entryCrew.getText().toString();
try{
FileOutputStream saveNewEvent1 = openFileOutput(textViewText, MODE_WORLD_READABLE);
OutputStreamWriter saveNewEvent2 = new OutputStreamWriter(saveNewEvent1);
try {
saveNewEvent2.write(timeHour);
} catch (IOException e) {
e.printStackTrace();
}
try {
saveNewEvent2.write(timeMinute);
} catch (IOException e) {
e.printStackTrace();
}
try {
saveNewEvent2.write(event);
} catch (IOException e) {
e.printStackTrace();
}
try {
saveNewEvent2.write(location);
} catch (IOException e) {
e.printStackTrace();
}
try {
saveNewEvent2.write(crew);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getBaseContext(), "Roger Roger", Toast.LENGTH_LONG).show();
}catch(FileNotFoundException e){
e.printStackTrace();
}
Log.i("info","The event is: "+timeHour+timeMinute+event+location+crew);
}
}

Attempt to invoke virtual method 'java.io.FileOutputStream android.content.Context.openFileOutput(java.lang.String, int)' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
For some reason in my application, when I try to call openFileOutput(), it throws a NullPointerException and I am not sure what is causing it. I have made sure that all the parameters of the method are not null, but for some reason my app still throws a NullPointerException. Any suggestions?
My MainActivity class
public class MainActivity extends AppCompatActivity {
private static final String TAG_NEWS_FRAGMENT = "news_fragment";
private static final String TAG_SPORTS_FRAGMENT = "sports_fragment";
Context context = MainActivity.this;
private final String[] CATEGORY_NAMES = {"news", "sports"};
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private ProgressBar mProgressBar;
private CoordinatorLayout coordinatorLayout;
private PUNewsFragment mPUNewsFragement;
private PUSportsFragment mPUSportsFragement;
private List<NewspaperMetaObject> newsItems;
private List<List<NewspaperMetaObject>> categories;
private boolean doesFileExist;
private boolean isWebsiteOnline;
private FragmentManager fm;
private ProgressBar pb;
private boolean doRefresh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
doRefresh = false;
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
Toast.makeText(this, "Loading...", Toast.LENGTH_SHORT).show();
pb = (ProgressBar) findViewById(R.id.progressBar);
try {
isWebsiteOnline = new checkWebsiteStatus().execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
doesFileExist = new File(context.getFilesDir() + "/news").exists();
new RetrieveNewspaperMeta().execute(CATEGORY_NAMES);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new PUNewsFragment(), "News");
adapter.addFragment(new PUSportsFragment(), "Sports");
viewPager.setAdapter(adapter);
}
public void refresh(String[] str) {
doRefresh = true;
new RetrieveNewspaperMeta().execute(str);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
private class RetrieveNewspaperMeta extends AsyncTask<String, Integer, Wrapper> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Wrapper doInBackground(String... params) {
Document doc = null;
categories = new ArrayList<>();
if (!doesFileExist && doRefresh) {
for (int i = 0; i < params.length; i++) {
newsItems = new ArrayList<>();
try {
Log.i("DEBUG", params[i]);
URL url = new URL("http://www.dailyprincetonian.com/category/" + params[i] + "/");
doc = Jsoup.connect(url.toString()).get();
Elements content = doc.select("article.tease-post");
System.out.println();
System.out.println(content);
int count = 0;
NewspaperMetaObject parser;
while (!content.eq(count).isEmpty()) {
parser = new NewspaperMetaObject(content.eq(count));
newsItems.add(parser);
count++;
}
categories.add(newsItems);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for (NewspaperMetaObject o : newsItems) {
try {
Elements text = Jsoup.connect(o.getDoc().select("h3.h2 a").attr("href")).get().select("section.article-content").select("div.article-bd").select("p");
o.setArticleText(text.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new Wrapper(categories, params);
} else {
for (int i = 0; i < params.length; i++) {
newsItems = new ArrayList<>();
try {
FileInputStream fis = openFileInput(params[i]);
ObjectInputStream is = new ObjectInputStream(fis);
newsItems = (List<NewspaperMetaObject>) is.readObject();
is.close();
fis.close();
categories.add(newsItems);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return new Wrapper(categories, params);
}
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(final Wrapper wrapper) {
super.onPostExecute(wrapper);
android.os.Handler mHandler = new android.os.Handler();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (!doRefresh) {
PUNewsFragment.newsItems = categories.get(0);
PUSportsFragment.newsItems = categories.get(1);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
fm = getSupportFragmentManager();
mPUNewsFragement = (PUNewsFragment) fm.findFragmentByTag(TAG_NEWS_FRAGMENT);
mPUSportsFragement = (PUSportsFragment) fm.findFragmentByTag(TAG_SPORTS_FRAGMENT);
if (mPUNewsFragement == null && mPUSportsFragement == null) {
mPUNewsFragement = new PUNewsFragment();
mPUSportsFragement = new PUSportsFragment();
fm.beginTransaction().add(mPUNewsFragement, TAG_NEWS_FRAGMENT).commit();
fm.beginTransaction().add(mPUSportsFragement, TAG_SPORTS_FRAGMENT).commit();
}
} else {
for (int i = 0; i < wrapper.params.length; i++) {
switch (wrapper.params[i]) {
case "news":
PUNewsFragment.newsItems = categories.get(0);
PUNewsFragment.adapter.notifyDataSetChanged();
break;
case "sports":
PUSportsFragment.newsItems = categories.get(1);
PUSportsFragment.adapter.notifyDataSetChanged();
break;
}
}
}
if (pb != null) {
pb.setVisibility(View.GONE);
}
Log.i("DEBUG", "DONE!");
if (doRefresh) {
context = MainActivity.this;
for (int i = 0; i < wrapper.params.length; i++) {
try {
FileOutputStream fos = context.openFileOutput(wrapper.params[i], 0);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(newsItems);
os.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
doRefresh = false;
}
}, 1000);
}
}
private class checkWebsiteStatus extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
try {
URL url = new URL("http://www.dailyprincetonian.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
urlConnection.disconnect();
return true;
} catch (IOException e) {
}
return false;
}
}
private class Wrapper {
List<List<NewspaperMetaObject>> categories;
String[] params;
public Wrapper(List<List<NewspaperMetaObject>> categories, String[] params){
this.categories = categories;
this.params = params;
}
}
}
Snippet of where the Exception is being thrown
if (doRefresh) {
context = MainActivity.this;
for (int i = 0; i < wrapper.params.length; i++) {
try {
FileOutputStream fos = context.openFileOutput(wrapper.params[i], 0);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(newsItems);
//os.flush();
os.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It looks like the wrapper variable is declared (therefore you can do a
for (int i = 0; i < wrapper.params.length; i++)
without any problem) but all items in the array may be null referenced, wich is the cause of the NPE.

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;
}
}
}

Categories

Resources