Reading and writing a serialized object in android - java

I've been searching on here but can't seem to find what works. I'm trying to write a simple object list to a serialized file and can't seem to locate the file in android. It's my first time building an app and I had this working in netbeans by pointing to src/list.ser, however, this doesn't work in android studio. I guess my question is where do I place the ser file and how do I point to it in the code? Here is my code:
ListActivity:
public class ListActivity extends Activity implements Serializable {
private ArrayList<Item> list;
public List() throws Exception {
list = new ArrayList<Item>();
}
public void addItem(String name) {
list.add(new Item(name));
}
public void addCurrentList() throws Exception{
String pathToAppFolder = getExternalFilesDir(null).getAbsolutePath();
String filePath = pathToAppFolder +File.separator + "list.ser";
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filePath));
os.writeObject(list);
os.close();
}
catch (Exception e) {
System.out.println("NOPE NOPE NOPE NOPE");
}
}
public void addItem(String name, int price) {
list.add(new Item(name, price));
}
public ArrayList<Item> populate() {
return list;
}
public void record() {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("src/list.ser"));
ArrayList<Item> list2 = (ArrayList<Item>) in.readObject();
System.out.println(list2);
list = list2;
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
private List tester;
private ListView lv;
private EditText gg;
private Button button;
private Button clearButton;
private ArrayList list;
String pathToAppFolder = getExternalFilesDir(null).getAbsolutePath();
String filePath = pathToAppFolder + File.separator + "list.ser";
#Override
protected void onDestroy() {
try {
tester.addCurrentList();
} catch (Exception e) {
e.printStackTrace();
}
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//create the list
lv = (ListView) findViewById(R.id.listDisplay);
ListView mine = lv;
list = new ArrayList<String>();
try {
tester = new List();
}
catch (Exception e) {
}
for (Item item : tester.populate()) {
list.add(item);
}
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);
lv.setAdapter(arrayAdapter);
final TextView firstTextView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
clearButton = (Button) findViewById(R.id.clear);
gg = (EditText) findViewById(R.id.item);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String no = gg.getText().toString();
if (!no.isEmpty()) {
tester.addItem(no);
arrayAdapter.add(no);
arrayAdapter.notifyDataSetChanged();
gg.setText("");
}
}
});
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
arrayAdapter.clear();
arrayAdapter.notifyDataSetChanged();
}
});
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = lv.getItemAtPosition(position).toString();
arrayAdapter.remove(arrayAdapter.getItem(position));
arrayAdapter.notifyDataSetChanged();
}
});
}
#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;
}
}

First of all make sure that you have permission to write to the external storage.
as,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
You can use,
public void addCurrentList() throws Exception{
String pathToAppFolder = getExternalFilesDir(null).getAbsolutePath();
String filePath = pathToAppFolder +File.seperator + "list.ser";
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filePath));
os.writeObject(list);
os.close();
}
catch (Exception e) {
System.out.println("");
}
}
and the use create a file path from that as,
String filePath = pathToAppFolder +File.seperator + "Test.text";
and then where ever you want to read this file again, you can recreate the path. Because you have access to the context from the android code
EDIT
You can not access the context as you do in your code. You can do it in your onCreate method. I have added only the necessary parts.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pathToAppFolder = getExternalFilesDir(null).getAbsolutePath();
filePath = pathToAppFolder + File.separator + "list.ser";
//create the list
Oh my god, I had to go into great lengths to answer your question. Here it is, Your List class is not an Activity in your application. It is just a class. So I suggest you to remove those inheritance first. remove this extends Activity. And I suggest you to change the List class name to something else. Because, List is a defined keyword and its not a best practice to do so.
Change the method in List Activity as below.
public void addCurrentList(String filePath) throws Exception
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filePath));
os.writeObject(list);
os.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void record(String filePath) {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath));
ArrayList<Item> list2 = (ArrayList<Item>) in.readObject();
System.out.println(list2);
list = list2;
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
In your MainActivity, onDestroy Method,
change the code to,
tester.addCurrentList(filePath);

Related

how can I show toast message when text section is blank and the button gets pressed (in android studio)?

I have Created ToDo list app in android studio. i want to show a toast message when the button pressed while there is no text in it. like "Please enter Text". and also prevent creating any blank list. i have two java class files. MainActivity and FileHelper
MainActivity (code):
public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
private EditText ItemET;
private Button btn;
private ListView itemList;
private ArrayList<String> items;
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ItemET = findViewById(R.id.item_edit_text);
btn = findViewById(R.id.add_btn);
itemList = findViewById(R.id.item_list);
items = FileHelper.readData(this);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);
itemList.setAdapter(adapter);
btn.setOnClickListener(this);
itemList.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.add_btn:
String ItemEntered = ItemET.getText().toString();
adapter.add(ItemEntered);
ItemET.setText("");
FileHelper.writeData(items, this);
Toast.makeText(this, "item Added", Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
items.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(this, "Deleted", Toast.LENGTH_SHORT).show();
}
}
FileHelper (code):
public class FileHelper {
public static final String FILENAME = "listinfo.dat";
public static void writeData(ArrayList<String> items, Context context){
try {
FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(items);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static ArrayList<String> readData(Context context) {
ArrayList<String> itemList = null;
try {
FileInputStream fis = context.openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
itemList = (ArrayList<String>) ois.readObject();
} catch (FileNotFoundException e) {
itemList = new ArrayList<>();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return itemList;
}
}
Have a look at below code.
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.add_btn:
String ItemEntered = ItemET.getText().toString();
if(ItemEntered.trim().isEmpty()){
Toast.makeText(getApplicationContext(), "Please Enter some detail", Toast.LENGTH_LONG).show();
} else {
adapter.add(ItemEntered);
ItemET.setText("");
FileHelper.writeData(items, this);
Toast.makeText(this, "item Added", Toast.LENGTH_SHORT).show();
}
break;
}
}
Check this code:
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.add_btn:
if(!TextUtils.isEmpty(ItemET.getText().toString())){
String ItemEntered = ItemET.getText().toString();
adapter.add(ItemEntered);
ItemET.setText("");
FileHelper.writeData(items, this);
Toast.makeText(this, "item Added", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Please enter Text", Toast.LENGTH_SHORT).show();
}
break;
}
}

How to send values from an arraylist from AsyncTask class to another class in Android?

I have the next problem, I tried to send Arraylist<string> values from AsyncTask class to other class call graphics but I don’t know what I do wrong and how to get Arraylist<string> values in the other class, because I have a lot of sintaxis errors I my code
AsyncTask class
public class fetch extends AsyncTask<Void,Void,ArrayList<String>> {
//v funcional
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected ArrayList<String> doInBackground(Void... voids) {
String Id ="";
String Time ="";
String Pressure="";
ArrayList<String> IdArray = new ArrayList<String>();
ArrayList<String> TimeArray = new ArrayList<String>();
ArrayList<String> PressureArray = new ArrayList<String>();
String IdS=""+IdArray;
String TimeS=""+TimeArray;
String PresureS=""+PressureArray;
data.set(1,TimeS);
data.set(2,TimeS);
data.set(3,TimeS);
return data;
}
#Override
protected void onPostExecute(ArrayList<String> result){
super.onPostExecute(result);
Graphics.data.setText(data);
}}
The graphics class
public class Graphics extends AppCompatActivity {
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.graphics);
Button firstButton = (Button) findViewById(R.id.json);
data = (TextView) findViewById(R.id.msgTxt);
firstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fetch process = new fetch();
ArrayList<String> data= process.execute();
data.get(1);
}
});
}
you can create an interface which your "Graphics" implements it , and pass it to your AsyncTask class.
like this
public interface BlaBlaBla {
void doBla(ArrayList<String> myBla);
}
and in your "Graphics" :
class Graphics extends AppCompatActivity implements BlaBlaBla {
fetch process = new fetch(this);
}
and for asyncClass :
public class fetch extends AsyncTask<Void,Void,ArrayList<String>> {
//constructor
BlaBlaBla bla;
public fetch(BlaBlaBla bla){
this.bla=bla;
}
//when your task is complete use bla.doBla(pass your array here);
}
my solution
Fetch class
public class Fetch extends AsyncTask<Void,Void,String[][]> {
public static int KEY = 0;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected String[][] doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
String url = "http:xxxxxxx/xxx.json";
String jsonStr = sh.makeServiceCall(url);
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonStr);
int nTiempos=jsonObj.length();
String[] IdKeyArray = new String[nTie];
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(String.valueOf(i));
IdKeyArray[i] = c.getString("Key");
String[][] valores={IdKeyArray};
return valores;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
And this is the "call" the other class where I get the values
private String[][] valores;
Fetch process = new Fetch();
process.execute();
try {
valores=process.get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
pm.setText(String.valueOf(valores[Fetch.Key][0]));
}
}
}

Android Studio- Save custom class (with ArrayList) to a file

I've tried a few dozen tutorials and guides off stackoverflow and other sites to try and get this to work right. The app in question has a custom class that holds a list, with items that have a list within them. Ideally I'd like to be able to save from other activities when they close or are paused. The issue I run into is that when I close another activity (by pressing the back button), it shows a log of the save message. But when I open it back up instead of loading the info it should have saved it shows an blank list. Here's my code:
This is the main activity where the custom class is referenced and the save and load methods can be called:
public class ReminderList extends AppCompatActivity {
public static ListHolder Lholder;
public static ArrayList<ReminderType> AllReminders=new ArrayList<>();
public reminderCAdapter adapter;
public static ReminderType currentReminderType;
public static ItemType currentItemType;
public static TimeType currentTimesType;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder_list);
//generate list
File file=new File("f.rem");
if(file.exists()) {
try {
LoadData();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
AllReminders=Lholder.Rlist;
}
adapter=new reminderCAdapter(AllReminders,this);
ReminderType r1=new ReminderType("Thing1");
//AllReminders.add(r1);
ReminderType r2=new ReminderType("Thing2");
//AllReminders.add(r2);
//instantiate custom adapter
//MyCustomAdapter adapter = new MyCustomAdapter(AllReminders, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.listView);
lView.setAdapter(adapter);
}
public void onResume(){
super.onResume();
adapter.notifyDataSetChanged();
}
public static void SaveData() throws IOException {
Log.e("Saving Data", "trying");
FileOutputStream fos=new FileOutputStream("f.rem");
ObjectOutputStream oos= new ObjectOutputStream(fos);
oos.writeObject(Lholder);
oos.close();
}
public void LoadData() throws IOException, ClassNotFoundException {
Log.e("Loading Data", "trying");
FileInputStream fis=new FileInputStream("f.rem");
ObjectInputStream ois=new ObjectInputStream(fis);
Lholder=(ListHolder) ois.readObject();
ois.close();
}
public void AddToList(View view){
Intent intent = new Intent(this,ReminderSettings.class);
intent.putExtra("Type", "new");
startActivity(intent);
}
}
The other activity calls the save function like so:
#Override
protected void onStop() {
super.onStop(); // Always call the superclass method first
try {
ReminderList.SaveData();
} catch (IOException e) {
e.printStackTrace();
}
}
Here's a little list of the most recent posts Ive tried:
How to create a file on Android Internal Storage?
http://www.101apps.co.za/articles/using-android-s-file-system-for-saving-application-data-part-1-saving-files.html
If anyone can help me understand why this isn't working or what I need to do, I would greatly appreciate it.
Thanks much
I was unable to save it to a file without turning the arrays into a json string and nest the other arrays in it:
public class ReminderList extends AppCompatActivity {
public static ArrayList<ReminderType> AllReminders=new ArrayList<>();
public reminderCAdapter adapter;
public static ReminderType currentReminderType;
public static ItemType currentItemType;
public static TimeType currentTimesType;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.context=this;
setContentView(R.layout.activity_reminder_list);
//generate list
try {
LoadData();
} catch (IOException | ClassNotFoundException | JSONException e) {
e.printStackTrace();
}
alarmMan=(AlarmManager) getSystemService(ALARM_SERVICE);
adapter=new reminderCAdapter(AllReminders,this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.listView);
lView.setAdapter(adapter);
}
public void onResume(){
super.onResume();
adapter.notifyDataSetChanged();
}
public static void SaveData(Context context) throws IOException, JSONException {
Log.e("Saving Data", "trying");
JSONArray reminderData=new JSONArray();
JSONObject reminder;
JSONArray jItemData;
JSONObject jItem;
JSONArray jTimeData;
JSONObject jTime;
for(int i=0; i<AllReminders.size();i++){
//create the reminder item
reminder=new JSONObject();
jItemData=new JSONArray();
reminder.put("RemName",AllReminders.get(i).ReminderName);
//create each of the itemtype items
for(int j=0; j<AllReminders.get(i).Items.size();j++){
jItem=new JSONObject();
jTimeData=new JSONArray();
jItem.put("iName",AllReminders.get(i).Items.get(j).ItemName);
jItem.put("iNote",AllReminders.get(i).Items.get(j).AdditionalNote);
//create each time item
for(int h=0; h<AllReminders.get(i).Items.get(j).Times.size();h++){
jTime=new JSONObject();
jTime.put("hr",AllReminders.get(i).Items.get(j).Times.get(h).hour);
jTime.put("min",AllReminders.get(i).Items.get(j).Times.get(h).minute);
jTimeData.put(jTime);
}
//String tList=jTimeData.toString();
jItem.put("timeList",jTimeData);
jItemData.put(jItem);
}
//String iList=jItemData.toString();
reminder.put("itemList",jItemData);
Log.e("reminderItem", reminder.toString());
reminderData.put(reminder);
}
String remList=reminderData.toString();
FileOutputStream fos=context.openFileOutput("savedData",MODE_PRIVATE);
fos.write(remList.getBytes());
fos.close();
}
public void LoadData() throws IOException, ClassNotFoundException, JSONException {
Log.e("Loading Data", "trying");
FileInputStream fis=openFileInput("savedData");
BufferedInputStream bis= new BufferedInputStream(fis);
StringBuffer b=new StringBuffer();
while(bis.available() !=0){
char c=(char) bis.read();
b.append(c);
}
bis.close();
fis.close();
JSONArray reminderData= new JSONArray(b.toString());
//Log.e("b string", b.toString());
for(int i=0; i<reminderData.length();i++){
JSONObject remObj=reminderData.getJSONObject(i);
String rName=remObj.getString("RemName");
//Log.e("Rname",rName);
ReminderType remi=new ReminderType(rName);
JSONArray itemArray=remObj.getJSONArray("itemList");
for(int h=0; h<itemArray.length();h++){
JSONObject itemObj= itemArray.getJSONObject(h);
String iName=itemArray.getJSONObject(h).getString("iName");
//Log.e("iName",iName);
ItemType iTem= new ItemType(iName);
JSONArray timeArray=itemObj.getJSONArray("timeList");
for(int j=0; j<timeArray.length();j++){
JSONObject timeObj=timeArray.getJSONObject(j);
int hr=timeObj.getInt("hr");
int min=timeObj.getInt("min");
TimeType tIme=new TimeType(hr,min);
tIme.SetDisplayTime();
iTem.Times.add(tIme);
}
remi.Items.add(iTem);
}
AllReminders.add(remi);
}
}
public void AddToList(View view) throws IOException, JSONException {
Intent intent = new Intent(this,ReminderSettings.class);
intent.putExtra("Type", "new");
startActivity(intent);
}
}

Unable to fetch return value from a method in Java

I want to create a sidebar using values fetch from my servers.
But the values that I am trying to fetch from the method which holds the return value is causing error. I am unable to call this method.
Here's the code:
public class MainActivity extends AppCompatActivity {
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
public String returnnumfromAsyncTask;
private TextView setTextValue;
private TextView textViewid;
private Button buttonHit;
private String var;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
/*textViewid = (TextView)findViewById(R.id.textViewid);
buttonHit = (Button)findViewById(R.id.buttonHit);
buttonHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute("http://xyz.co/tests/ems/query.php");
}
});*/
}
private void addDrawerItems() {
new JSONTask().execute("http://xyz.co/tests/ems/query.php");
JSONTask json = new JSONTask();
String myArray = json.myMethod();
String[] osArray = { "Android", "iOS", "Windows", "OS X", "Linux" };
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Time for an upgrade!", Toast.LENGTH_SHORT).show();
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Navigation!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#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;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class JSONTask extends AsyncTask<String,String,String> {
#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();
// connecting to the url
//Reading the data in bytes stream
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
//Reading the data by creating a buffer
StringBuffer buffer = new StringBuffer();
String line="";
while((line = reader.readLine())!= null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
List<String> list = new ArrayList<String>();
JSONArray array = parentObject.getJSONArray("kitten");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("if")+"\n");
}
/*String finalObject = parentObject.getString("name");
JSONArray parentArray = parentObject.getJSONArray("kitten");
StringBuffer finalBufferedData = new StringBuffer();
for(int i=0;i<parentArray.length();i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
int curr = finalObject.getInt("name");
//int bus = finalObject.getInt("bus");
finalBufferedData.append(curr + "\n" );
}*/
//return finalBufferedData.toString();
return list.toString();
// setting text view from the url
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally{
if(connection !=null) {
connection.disconnect();
}
try {
if (reader != null)
{
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//textViewid.setText(result);
myMethod(result);
}
public String myMethod(String result){
return result;
}
}
}
Notice the line:
String myArray = json.myMethod();
It tries to call a function myMethod() which returns a string value or rather an array which I get by executing asynctask.
But somehow I am not able to call myMethod from JSON asynctask function.
So my primary question is how to call a method which returns a value and thereby use it in my code?
Thanks in advance
AsyncTask.doInBackground() runs asynchronously.
You should run JSONTask like so:
private void addDrawerItems() {
new JSONTask().execute("http://xyz.co/tests/ems/query.php");
}
And move code that uses result of this task to JSONTask.onPostExecute():
public class JSONTask extends AsyncTask<String,String,String[]> {
#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();
//connecting to the url
//Reading the data in bytes stream
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
// Reading the data by creating a buffer
StringBuffer buffer = new StringBuffer();
String line="";
while((line = reader.readLine())!= null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
List<String> list = new ArrayList<String>();
JSONArray array = parentObject.getJSONArray("kitten");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("if")+"\n");
}
return list.toArray(new String[list.size()]);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally{
if(connection !=null) {
connection.disconnect();
}
try {
if (reader != null)
{
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
mAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, result);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Time for an upgrade!", Toast.LENGTH_SHORT).show();
}
});
}
}
Because doInBackground method of JSONTask class executed in background Thread,so:
JSONTask json = new JSONTask();
String myArray = json.myMethod();
these lines are executing just after call of execute method.
EITHER
use AsyncTask.get() method which will freeze UI Thread until doInBackground method execution not completed.
OR
Best way is use onPostExecute for setting Adapter for ListView.
EDIT :
As question in comment:
How do I use onPostExecute to sett adapter for ListView?
If JSONTask class is inner-class of MainActivity class then you can access all variables of MainActivity class in JSONTask directly.just move related code in onPostExecute method.
and if JSONTask class is separate class then pass Activity Context to JSONTask for accessing UI elements from normal java class as:
1. Add a constructor to JSONTask class for getting Activity Context as:
private Context mContext;
private ListView mDrawerList;
JSONTask(Context mContext, ListView mDrawerList){
this.mContext=mContext;
this.mDrawerList=mDrawerList;
}
2. Pass MainActivity.this as parameter when creating object of JSONTask class:
JSONTask objJSONTask=new JSONTask(MainActivity.this);
objJSONTask.execute("http://xyz.co/tests/ems/query.php");
3. Now use mContext and mDrawerList to show ListView in onPostExecute

Edit activity-shared ArrayList to be saved in SharedPreferences

I have an ArrayList<String> that I save in shared preference in Activity A. I access the list from a second activity (ListActivity). Activity A starts ListActivity for a result. When an item is clicked the ListActivity sends the string at that position to Activity A for use. A long click allows you to delete.
When I delete from the list, I want to save the new (the latest) list in sharedpreferences. PLEASE! How can I do this? I just need the List to popup, you do your thing, and it goes away after saving the newest list.
I tried so many ways (code is patchwork at this point) but the deleted item persists when I open ListActivity again after deleting the item.
My code is below...
Activity A:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write);
...
lyricTitle = (AutoCompleteTextView) findViewById(R.id.lyricTitle);
...
lyricTitle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// load in song when selected from auto-complete list
lyricHolder.setText(openSongFile(lyricTitle.getText().toString()));
}
});
lyricHolder = (EditText) findViewById(R.id.lyricHolder);
newSongBtn = (ImageView) findViewById(R.id.newSongBtn);
newSongBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (areFieldsNull(lyricTitle.getText().toString(),
lyricHolder.getText().toString()))
alertEmpty.show();
else {
/** There is some redundancy within performSave() here */
performSave();
lyricTitle.setText("");
lyricHolder.setText("");
}
}
});
...
findBtn = (Button) findViewById(R.id.findBtn);
findBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent showListIntent = new Intent(getApplicationContext(), pickActivity.class);
startActivityForResult(showListIntent, GET_SONG_CODE);
Log.i("TAG1", "Starting pickActivity.class for result");
}
});
saveBtn = (Button) findViewById(R.id.saveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
performSave();
}
});
...
// init sharedPreferences
colorPref = getSharedPreferences(COLOR_PREF, MODE_PRIVATE);
titlePref = getSharedPreferences(TITLE_PREF, MODE_PRIVATE);
externalSDPref = getSharedPreferences(EXTERNAL_SD_PREF, MODE_PRIVATE);
// load defaults of sharedPreferences
titleList = new ArrayList<>();
try {
titleList = (ArrayList<String>) ObjectSerializer
.deserialize(titlePref.getString(TITLE_PREF, ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
mSetTitleListAdapter(titleList);
...
} //end onCreate
private void mSetTitleListAdapter(ArrayList<String> List) {
autoCompleteAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
List
);
lyricTitle.setAdapter(autoCompleteAdapter);
}
...
private boolean areFieldsNull(String title, String song) {
// check if the text fields are empty
return (
title.isEmpty()||
title.equals(" ")||
title.equals(" ")||
song.isEmpty()||
song.equals(" ")||
song.equals(" ")
);
}
private void performSave() {
String title = lyricTitle.getText().toString();
String song = lyricHolder.getText().toString();
if(!areFieldsNull(title, song)) {
saveSongFile(title, song);
alertSave.show();
}
else
alertEmpty.show();
}
private void saveTitleArray() {
// save string array list in shared prefs
try {
prefEditor = titlePref.edit();
prefEditor.putString(TITLE_PREF, ObjectSerializer.serialize(titleList));
} catch (IOException e) {
e.printStackTrace();
}
prefEditor.apply();
}
private void saveSongFile(String title, String song) {
BufferedWriter bufferWriter = null;
try {
FileOutputStream fos = openFileOutput(title, Context.MODE_PRIVATE);
bufferWriter = new BufferedWriter(new OutputStreamWriter(fos));
bufferWriter.write(song);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(isExternalStoragePresent()&&externalSD_box.isChecked()){
// save to the SD card IF SD is found AND enableSD_box is checked
File path = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File songFile = new File (path, title + ".txt");
try {
OutputStream os = new FileOutputStream(songFile);
byte[] data = song.getBytes();
os.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
// new songs (but not updated songs) go to top
if (!titleList.contains(title))
titleList.add(0, title);
mSetTitleListAdapter(titleList);
saveTitleArray();
}
private String openSongFile(String title){
BufferedReader bufferReader = null;
StringBuilder builder = new StringBuilder();
try {
FileInputStream fis = openFileInput(title);
bufferReader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = bufferReader.readLine()) != null) {
builder.append(line + "\r\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return builder.toString();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// when pickActivity ListView returns result
Log.i("TAG1", "Activity data returned from pickActivity.class");
if (requestCode == GET_SONG_CODE && resultCode == RESULT_OK) {
String title = data.getData().toString();
lyricTitle.setText(title);
lyricHolder.setText(openSongFile(title));
Log.i("TAG1", "Result success\nSong loaded into edittext");
Toast.makeText(this, "\""+title+"\""+" selected", Toast.LENGTH_SHORT).show();
}
}
ListActivity:
public class pickActivity extends ListActivity {
ArrayList<String> songListArray;
SharedPreferences titlePref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick_song);
Log.i("TAG2", "pickActivity.class created");
// init string array from blank list or sharedPref saved data
titlePref = getSharedPreferences(writeActivity.TITLE_PREF, MODE_PRIVATE);
songListArray = new ArrayList<>();
try {
songListArray = (ArrayList<String>) ObjectSerializer
.deserialize(titlePref.getString(writeActivity.TITLE_PREF, ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
mSetListAdapter(songListArray);
Log.i("TAG2", "Extra received and set");
mSetListAdapter(songListArray);
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
Log.i("TAG2", "onItemLongClick()");
final AlertDialog.Builder confirmDel = new AlertDialog.Builder(pickActivity.this);
confirmDel.setTitle("Delete Song")
.setIcon(R.mipmap.ic_keeper)
.setMessage("Are you sure you want " +
"\"" + songListArray.get(position) +
"\"" + " gone?")
.setPositiveButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// system default is dismiss()
}
})
.setNegativeButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// delete song, title, then update title list
getApplicationContext().deleteFile(songListArray.get(position));
songListArray.remove(position);
Log.i("TAG2", "Item deleted from list");
updateSharedPref(titlePref, writeActivity.TITLE_PREF, songListArray);
mSetListAdapter(songListArray);
Toast.makeText(
getApplicationContext(),
"Deleted",
Toast.LENGTH_SHORT).show();
}
});
confirmDel.create().show();
return true;
}
});
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Log.i("TAG2", "onListItemClick()");
Intent resultIntent = new Intent(EXTRA_NAME, Uri.parse(songListArray.get(position)));
setResult(RESULT_OK, resultIntent);
finish();
}
private void mSetListAdapter(ArrayList<String> list) {
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
list
);
setListAdapter(arrayAdapter);
Log.i("TAG2", "ArrayList adapter set");
}
private void updateSharedPref(SharedPreferences sharedPref,
String prefFileName,
ArrayList<String> list) {
SharedPreferences.Editor editor = sharedPref.edit();
try {
editor.putString(prefFileName, ObjectSerializer.serialize(list));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
Log.i("TAG2", "SharedPref updated!");
}
}
Honestly, source code would help a lot in this case...
My best guess (without any code) would be, please make sure that you call
editor.apply();
and not
editor.commit();

Categories