With support, I have created a list of arrays that populates JSON data. When a user clicks on an item in the list of arrays, it takes them to an activity page that provides them more information about that particular item.
In particular, below are my 3 questions:
In the single item page, I added an "add more" button, and I would want that when the button is click, that particular item gets recorded until 3 different item in the list of arrays have been selected.
I would want to update the user of how many item have been selected thus far in a textview in the single item page.
I have added a confirm button, but I would want to set a condition, where it would only go to the next activity once 3 item have been selected.
Transmit the user recorded information to parse.com. Where every time, a user click on add more, it updates parse on the activity that have been selected by the user, where I could have three column for activity 1, activity 2, and activity 3 within my class.
Below is my list of arrays code:
public class EventsActivity extends Activity{
private static final String URL_WEB_SERVICE = "http://dooba.ca/analytics/ed.php";
private GridView gv;
private ArrayList<Events_List> container;
private ArrayList<Events_List> items;
public Uri list_item_bac;
public String list_item_name;
public String list_item_description;
public String single_list_item_description;
public String list_item_price;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.events_list_layout);
gv = (GridView) findViewById(R.id.gridview);
container = new ArrayList<Events_List>();
//download JSON
listDownload();
GridView s = (GridView) findViewById(R.id.gridview);
s.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(EventsActivity.this,EventSingleItemActivity.class);
intent.putExtra("list_item_name", container.get(position).getList_item_title());
intent.putExtra("single_list_item_description", container.get(position).getSingle_list_item_description());
startActivity(intent); //start Activity
}
});
}
public void listDownload(){
RequestQueue volley = Volley.newRequestQueue(this);
JsonObjectRequest json = new JsonObjectRequest(Method.GET, URL_WEB_SERVICE, null, ResponseListener(), ErrorListener());
volley.add(json);
}
private Response.Listener<JSONObject> ResponseListener() {
return new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//your JSON Array
JSONArray array = response.getJSONArray("list_item");
for(int i = 0; i < array.length(); i++){
container.add(convertirAnuncio(array.getJSONObject(i)));
}
} catch (JSONException e) {
e.printStackTrace();
}
gv.setAdapter(new AdapterEvents(getApplicationContext(),container));
}
};
};
private Response.ErrorListener ErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) { }
};
}
//object JSON
private final Events_List convertirAnuncio(JSONObject obj) throws JSONException {
long id = obj.getLong("id"); //id
String list_item_name = obj.getString("list_item_name");
String list_item_description = obj.getString("list_item_description");
String single_list_item_description = obj.getString("single_list_item_description");
Uri uri = Uri.parse(obj.getString("list_item_bac"));
return new Events_List(id,single_list_item_description,list_item_name,list_item_description,list_item_price, uri);
}
}
Below is my single item click page
public class EventSingleItemActivity extends Activity {
// Declare Variables
String list_item_name;
String list_item_description;
String list_item_price;
String single_list_item_description;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events_single_item);
Intent i = getIntent();
list_item_name = i.getStringExtra("list_item_name");
single_list_item_description = i.getStringExtra("single_list_item_description");
TextView txtname = (TextView) findViewById(R.id.name);
TextView txtsdescription = (TextView) findViewById(R.id.sdescription);
// Set results to the TextViews
txtname.setText(list_item_name);
txtsdescription.setText(single_list_item_description);
Button mConfirm2 = (Button)findViewById(R.id.bConfirm2);
mConfirm2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EventSingleItemActivity.this.startActivity(new Intent(EventSingleItemActivity.this, MatchingActivity.class));
}
});
Button mcancel = (Button)findViewById(R.id.bRemove);
mcancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EventSingleItemActivity.this.startActivity(new Intent(EventSingleItemActivity.this, EventsActivity.class));
}
});
}
}
I have looked into the following tutorial:
http://theopentutorials.com/tutorials/android/listview/android-multiple-selection-listview/
but this is not exactly what I want to achieve.
ArrayList< ArrayList > yourVar = new ArrayList< ArrayList >();
same should apply for a list, you can also use a 2d array, but those are annoying to fill.
Related
I parsed JSON data from URL into a list and now I want to create buttons with every item of the list, but I can't figured out how to do this. I'm not sure if the list is the best idea, but I this was the solution I found online.
public class SecondActivity extends AppCompatActivity {
private String TAG = SecondActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
private static String url = "https://ggysqqcz.p51.rt3.io/available-remotes/TV";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SecondActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray remotes = jsonObj.getJSONArray("remotes");
// looping through All Contacts
for (int i = 0; i < remotes.length(); i++) {
JSONObject c = remotes.getJSONObject(i);
String id = c.getString("id");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
SecondActivity.this, contactList,
R.layout.list_item, new String[]{"id"}, new int[]{button1});
lv.setAdapter(adapter);
}
}
public void onClickButton1(View view) {
startActivity(new Intent(getApplicationContext(), ThirdActivity.class));
}
}
This shows all the buttons, but obviously they all do the same thing when clicked because I have only button1. How can I make all the buttons do different activities?
I would like to suggest creating a custom adapter for your ListView which will have an onClick function for your button and based on the position of that item in your ListView, you can implement different actions in your onClick function. Hence I would like to suggest an adapter like the following.
public class ListAdapter extends ArrayAdapter<Item> {
private int resourceLayout;
private Context mContext;
private ArrayList<Contact> contacts;
public ListAdapter(Context context, int resource, ArrayList<Contact> contacts) {
super(context, resource, items);
this.resourceLayout = resource;
this.mContext = context;
this.contacts = contacts;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(mContext);
v = vi.inflate(resourceLayout, null);
}
Item p = getItem(position);
if (p != null) {
Button btn = (TextView) v.findViewById(R.id.button1);
if (btn != null) {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(position == 1) implementSomethingFor1();
else if (position == 2) implementSomethingFor2();
// ... Define the other implementations
}
});
}
}
return v;
}
}
And then use the adapter like the following.
ListView lv = (ListView) findViewById(R.id.list);
ListAdapter customAdapter = new ListAdapter(this, R.layout.list_item, contactList);
lv.setAdapter(customAdapter);
Please note that this is not an exact implementation. You should modify your custom adapter so that it serves your purpose.
try
lv.setonitemclicklisnter, this will create a method which will allow you to click on each and every item, you can write for example A Toast message inside this method so when you click on an item a Toast message will pop up.
You have several options:
Check the view parameter to determine what to do. You can use getTag() and setTag() to provide custom data on each button.
Create a custom adapter by extending SimpleAdapter. Override createView() and bindView() in order to provide custom behavior for each button, such as adding a different OnClickListener object to each button
Set the OnItemClickListener for the ListView. This provides a parameter for which position in the list view was clicked. You can use that to determine what to do or what data to pass to the new activity. You will likely want to use getItem() from your adapter to get the data for the current row.
Excuse my noobness. I just don't understand how to implement it to work with my code. What I'm doing is editing a name that's in a list view. When editing the name in "EditDeleteList" and get back to the previous activity (ListView) to see the name updated within the list view, nothing happens. I have to go out of the activity completely to see the change reflected. How do I get this to update? I implement an onActivityReult() method but then get this error message "java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference" so I removed it completely. How I could get the list view to update without getting that error message?
ListView.Java
public class ListView extends AppCompatActivity {
private static final String TAG = "ListView";
DatabaseHelper mDatabaseHelper;
Button btnAdd;
private EditText editText;
private android.widget.ListView listView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
mDatabaseHelper = new DatabaseHelper(this);
btnAdd = (Button) findViewById(R.id.btnAdd);
editText = (EditText) findViewById(R.id.editText);
listView = (android.widget.ListView) findViewById(R.id.lv);
ArrayList<String> list = getIntent().getStringArrayListExtra("myList");
android.widget.ListView lv = (android.widget.ListView) findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
//Takes user back to the main activity
ImageView ivBack = (ImageView) findViewById(R.id.ivBackArrow);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: pressed back arrow");
Intent intent = new Intent(ListView.this, MainActivity.class);
startActivity(intent);
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
addData(newEntry);
editText.setText("");
} else {
toastMessage("you must put something in the text field");
}
}
});
populateListView();
}
public void addData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Successfully inserted");
recreate();
} else {
toastMessage("Whoops, something went wrong");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
private void populateListView() {
Log.d(TAG, "populateListView: displaying data in the listview");
//get data and append to list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()) {
//get the value from the database in column 1
//set it to the arraylist
listData.add(data.getString(1));
}
//create arraylist and set it to the adapter
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
listView.setAdapter(adapter);
//set onclick listen to edit activity
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String name = adapterView.getItemAtPosition(position).toString();
Log.d(TAG, "onItemClick: you clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while (data.moveToNext()) {
itemID = data.getInt(0);
}
if (itemID > -1) {
Log.d(TAG, "onItemID: the ID is: " + itemID);
Intent editScreenIntent = new Intent(ListView.this, EditDeleteList.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
} else {
toastMessage("No ID found");
}
}
});
}
}
EditDeleteList.java
public class EditDeleteList extends AppCompatActivity {
private static final String TAG = "EditDeleteList";
DatabaseHelper mDatabaseHelper;
private ImageView ivDelete;
private ImageView ivApprove;
private EditText editHashtag;
private String selectedName;
private int selectedID;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_delete);
mDatabaseHelper = new DatabaseHelper(this);
editHashtag = (EditText) findViewById(R.id.editHashtag);
ivDelete = (ImageView) findViewById(R.id.ivDelete);
ivApprove = (ImageView) findViewById(R.id.ivApprove);
//get the intent extra from the ListView activity
final Intent receivedIntent = getIntent();
//get item ID passed as an extra
selectedID = receivedIntent.getIntExtra("id", -1);
//get name passed as an extra
selectedName = receivedIntent.getStringExtra("name");
//set text field to selected item text
editHashtag.setText(selectedName);
ivApprove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = editHashtag.getText().toString();
if (!item.equals(null)) {
mDatabaseHelper.updateName(item, selectedID, selectedName);
} else {
toastMessage("you must enter a #hashtag");
}
finish();
}
});
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
In the EditDeleteList.java I have an onClickListener that saves the changes and goes back to the previous activity by using finish();
ivApprove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = editHashtag.getText().toString();
if (!item.equals(null)) {
mDatabaseHelper.updateName(item, selectedID, selectedName);
} else {
toastMessage("you must enter a #hashtag");
}
finish();
}
});
Notify the adapter in some part of the activity lifecycle.
OnCreate() should not run when you go back (this is the reason you have to completely recreate the activity to see the list updated) so you should use OnRestart/OnStart/OnResume to notify the adapter to check for new items.
Check this image
this is the code:
public class MainActivity extends AppCompatActivity {
ListView listView;
ProgressBar progressBar;
String HTTP_JSON_URL = "http://10.0.2.2/positivity/all_subjects.php";
EditText editText;
List SubjectArrayList = new ArrayList();
ArrayAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listview1);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
editText = (EditText) findViewById(R.id.edittext1);
// Calling Method to Parese JSON data into listView.
new GetHttpResponse(MainActivity.this).execute();
// Calling EditText addTextChangedListener method which controls the EditText type sequence.
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//Updating Array Adapter ListView after typing inside EditText.
MainActivity.this.arrayAdapter.getFilter().filter(charSequence);
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
}
});
// Adding On item click listener on ListView.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
String Item = parent.getItemAtPosition(position).toString();
// Showing ListView click item using Toast message on screen.
Toast.makeText(MainActivity.this, Item, Toast.LENGTH_LONG).show();
}
});
}
// Creating GetHttpResponse message to parse JSON.
public class GetHttpResponse extends AsyncTask<Void, Void, Void> {
// Creating context.
public Context context;
// Creating string to hold Http response result.
String ResultHolder;
// Creating constructor .
public GetHttpResponse(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
// Sending the Http URL into HttpServicesClass to parse JSON.
HttpServicesClass httpServiceObject = new HttpServicesClass(HTTP_JSON_URL);
try {
httpServiceObject.ExecutePostRequest();
// If the server response code = 200 then JSON parsing start.
if (httpServiceObject.getResponseCode() == 200) {
// Adding Http response into ResultHolder string.
ResultHolder = httpServiceObject.getResponse();
// If there is response present into ResultHolder.
if (ResultHolder != null) {
// Creating JSONArray and set it to null.
JSONArray jsonArray = null;
try {
// Adding ResultHolder into JSONArray.
jsonArray = new JSONArray(ResultHolder);
// Creating JSONObject.
JSONObject jsonObject;
// Starting for loop at the end of jsonArray length.
for (int i = 0; i < jsonArray.length(); i++) {
// Adding JSON array object .
jsonObject = jsonArray.getJSONObject(i);
// Adding the JSON parse object into SubjectArrayList.
SubjectArrayList.add(jsonObject.getString("subject_Name").toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
// If something goes wrong then showing the error message on screen.
Toast.makeText(context, httpServiceObject.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// This block will execute after done all background processing.
#Override
protected void onPostExecute(Void result) {
// Hiding the progress bar after done loading JSON.
progressBar.setVisibility(View.GONE);
// Showing the ListView after done loading JSON.
listView.setVisibility(View.VISIBLE);
// Setting up the SubjectArrayList into Array Adapter.
arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_2, android.R.id.text1, SubjectArrayList);
// Passing the Array Adapter into ListView.
listView.setAdapter(arrayAdapter);
}
}
}
In your activity, where you defined your listview
you write
public class MainActivity extends AppCompatActivity {
ListView listView;
ProgressBar progressBar;
String HTTP_JSON_URL = "http://10.0.2.2/positivity/all_subjects.php";
EditText editText;
List SubjectArrayList = new ArrayList();
ArrayAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listview1);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
editText = (EditText) findViewById(R.id.edittext1);
// Calling Method to Parese JSON data into listView.
new GetHttpResponse(MainActivity.this).execute();
// Calling EditText addTextChangedListener method which controls the EditText type sequence.
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//Updating Array Adapter ListView after typing inside EditText.
MainActivity.this.arrayAdapter.getFilter().filter(charSequence);
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
}
});
// Adding On item click listener on ListView.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
//ItemClicked item = parent.getItemAtPosition(position);
if(position==0)
{
Intent intent = new Intent(MainActivity.this,one.class);
//based on item add info to intent
startActivity(intent);
}
}
});
}
// Creating GetHttpResponse message to parse JSON.
public class GetHttpResponse extends AsyncTask<Void, Void, Void> {
// Creating context.
public Context context;
// Creating string to hold Http response result.
String ResultHolder;
// Creating constructor .
public GetHttpResponse(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
// Sending the Http URL into HttpServicesClass to parse JSON.
HttpServicesClass httpServiceObject = new HttpServicesClass(HTTP_JSON_URL);
try {
httpServiceObject.ExecutePostRequest();
// If the server response code = 200 then JSON parsing start.
if (httpServiceObject.getResponseCode() == 200) {
// Adding Http response into ResultHolder string.
ResultHolder = httpServiceObject.getResponse();
// If there is response present into ResultHolder.
if (ResultHolder != null) {
// Creating JSONArray and set it to null.
JSONArray jsonArray = null;
try {
// Adding ResultHolder into JSONArray.
jsonArray = new JSONArray(ResultHolder);
// Creating JSONObject.
JSONObject jsonObject;
// Starting for loop at the end of jsonArray length.
for (int i = 0; i < jsonArray.length(); i++) {
// Adding JSON array object .
jsonObject = jsonArray.getJSONObject(i);
// Adding the JSON parse object into SubjectArrayList.
SubjectArrayList.add(jsonObject.getString("subject_Name").toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
// If something goes wrong then showing the error message on screen.
Toast.makeText(context, httpServiceObject.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// This block will execute after done all background processing.
#Override
protected void onPostExecute(Void result) {
// Hiding the progress bar after done loading JSON.
progressBar.setVisibility(View.GONE);
// Showing the ListView after done loading JSON.
listView.setVisibility(View.VISIBLE);
// Setting up the SubjectArrayList into Array Adapter.
arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_2, android.R.id.text1, SubjectArrayList);
// Passing the Array Adapter into ListView.
listView.setAdapter(arrayAdapter);
}
}
}
Try this one example, actually its same as anywhere else
mListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intentToYoklamaAl = new Intent(CurrentActivity.this, SecondActivity.class);
// intentToYoklamaAl.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intentToYoklamaAl);
// overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
// finish();
}
});
I need to keep and restore the results of a search while rotating the screen by override the onSaveInstanceState and onRestoreInstanceState... I don't know how to do this and where to use it.
someone got a clue about this ?
This is a part of the MainActivity:
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = MainActivity.class.getName();
/**
* URL for book data from the Google books dataset
*/
private static final String G_BOOKS_REQUEST_URL =
"https://www.googleapis.com/books/v1/volumes?q=";
/**
* Adapter for the list of books
*/
private BookAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
..............
Save the URL search result json/xml in savedInstanceState. When rotate screen test if result exist in savedInstanceState
savedInstanceState.putString("result", <serach result json/xml>);
final EditText searchTextView = (EditText) findViewById(R.id.search_bar);
Button searchButton = (Button) findViewById(R.id.search_button);
ListView bookListView = (ListView) findViewById(R.id.list);
mAdapter = new BookAdapter(this, new ArrayList<Book>());
bookListView.setAdapter(mAdapter);
bookListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Book currentBook = mAdapter.getItem(position);
Uri bookUri = Uri.parse(currentBook.getmUrl());
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, bookUri);
startActivity(websiteIntent);
}
});
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String newQuery = searchTextView.getText().toString();
BookAsyncTask task = new BookAsyncTask();
task.execute(G_BOOKS_REQUEST_URL + newQuery);
}
});
}
#Override
protected List<Book> doInBackground(String... urls) {
// Don't perform the request if there are no URLs, or the first URL is null
if (urls.length < 1 || urls[0] == null) {
return null;
}
List<Book> result = QueryUtils.fetchBookData(urls[0]);
return result;
}
#Override
protected void onPostExecute(List<Book> data) {
mAdapter.clear();
if (data != null && !data.isEmpty()) {
mAdapter.addAll(data);
}
}
}
}
I am trying to load some items from JSON, I am able to get and parse the JSON and load it up in listview when using one activity. However, I want to use a LoadJSON.class to load the JSON, and then the activity can call the json passed and show it in the listview in that activity.
Here is what I have tried:
SongsManager.class
public class SongsManager {
private String TAG = SongsManager.class.getSimpleName();
private static final String API_URL = "http://xxxxxxxxxxxxx.com/jame/mp3/songlist.json";
private List<SolTracks> solTracksList;
private ProgressDialog pDialog;
private final Activity activity;
public SongsManager(Activity activity) {
this.activity = activity;
solTracksList = new ArrayList<>();
pDialog = new ProgressDialog(activity);
fetchSongs();
}
private void fetchSongs() {
pDialog.setMessage("Fetching Playlist...");
pDialog.show();
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(API_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "Responser = " + response.toString());
pDialog.hide();
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
String songTitle = movieObj.getString("title");
String songId = movieObj.getString("id");
String streamUrl = movieObj.getString("stream_url");
SolTracks m = new SolTracks(songTitle, songId, streamUrl);
solTracksList.add(m);
Collections.sort(solTracksList, new TrackComparator());
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
pDialog.hide();
Snackbar snackbar = Snackbar
.make(activity.findViewById(android.R.id.content), "PLEASE CHECK YOUR INTERNET", Snackbar.LENGTH_LONG)
.setAction("DISMISS", new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
// Changing snackbar background
snackbar.getView().setBackgroundColor(ContextCompat.getColor(activity, R.color.colorPrimary));
// Changing message text color
snackbar.setActionTextColor(Color.YELLOW);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.WHITE);
snackbar.show();
}
});
req.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
public List<SolTracks> getList() {
return solTracksList;
}
Activity class
public class TheMain1 extends AppCompatActivity {
private SwipeRefreshLayout swipeRefreshLayout;
private String TAG = TheMain1.class.getSimpleName();
private static final String API_URL = "http://xxxxxxxxxxx.com/jame/mp3/songlist.json";
private ListView listView;
private SolTracksAdapter adapter;
private ProgressDialog pDialog;
private List<SolTracks> songslist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView) findViewById(R.id.track_list_view);
songslist = new ArrayList<>();
SongsManager songsManager = new SongsManager(this);
songslist = songsManager.getList();
adapter = new SolTracksAdapter(this, songslist);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SolTracks track = songslist.get(position);
final String stream_url = track.stream_url;
final String id_url = track.id;
Intent intent = new Intent(TheMain1.this, PlayerActivity.class);
intent.putExtra("songPosition", position);
intent.putExtra("streamUrl", stream_url);
startActivity(intent);
}
}
);
}
As it is right now, I know the JSON is loaded from SongsManager, but its just not displaying in the listview of the Activity class. Can anyone help, and show what I'm doing wrong? Thanks
I was able to fix this by implementing Parcelable to send the list to the receiving activity.
public class SolTracks implements Parcelable {
public String title;
public String id;
public String stream_url;
}
Sending the list from the Activity A:
Intent intent = new Intent(TheMain.this, PlayerActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("mylist", solTracksList);
intent.putExtras(bundle);
intent.putExtra("songPosition", position);
startActivity(intent);
and then receiving in Activity B:
Bundle extras = getIntent().getExtras();
if (extras != null) {
songPosition = extras.getInt("songPosition");
trackList = extras.getParcelableArrayList("mylist");
}