I am generating buttons from the data I get from my JSON Object/Array. Getting from API.
Currently I have 20 loops so to say (20 data, 20 buttons).
The xml / layout for the button looks like this:
<Button
android:id="#+id/details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Currently the code to get the data and print it in my layout looks something like this:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://192.168.178.32:8888/test/public/index";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
contactList = new ArrayList<>();
new GetContacts().execute();
lv = (ListView) findViewById(R.id.list);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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 {
// Getting JSON Array node
JSONArray jsonArray = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String description = c.getString("description");
// tmp hash map for single contact
HashMap<String, String> data = new HashMap<>();
// adding each child node to HashMap key => value
data.put("id", id);
data.put("name", name);
data.put("description", description);
// adding contact to contact list
contactList.add(data);
}
} 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();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"name", "description"}, new int[]{R.id.name,
R.id.description, R.id.release_at});
lv.setAdapter(adapter);
}
And my Adapter looks like this:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private List<String> friends;
private Activity activity;
public RecyclerAdapter(Activity activity, List<String> friends, ArrayList<HashMap<String, String>> contactList) {
this.friends = friends;
this.activity = activity;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
//inflate your layout and pass it to view holder
LayoutInflater inflater = activity.getLayoutInflater();
View view = inflater.inflate(android.R.layout.simple_list_item_1, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder viewHolder, int position) {
viewHolder.item.setText(friends.get(position));
}
#Override
public int getItemCount() {
return (null != friends ? friends.size() : 0);
}
/**
* View holder to display each RecylerView item
*/
protected class ViewHolder extends RecyclerView.ViewHolder {
private TextView item;
public ViewHolder(View view) {
super(view);
item = (TextView) view.findViewById(android.R.id.text1);
}
}
}
My idea is to click on each button and show the related data in another activity with more detail.
But how can I run through a loop and get the correct button (id) and create an new Activity with its related data.
In your adapter's getView method, you can set a onClickLister to the button in that row which will have a reference to that row's data. Use an intent to start the detailed activity and add the clicked item's data as an extra.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//Inflate your row
button.setOnClickListener(new OnClickListener(){
#Override
//On click function
public void onClick(View view) {
HashMap<String, String> item = contactsList.get(position);
//Create the intent to start another activity
Intent intent = new Intent(view.getContext(), DetailActivity.class);
intent.putExtra("data", item);
view.getContext().startActivity(intent);
}
});
});
In the receiving activity, you can get the data from the intent :
HashMap<String, String> data = getIntent().getExtras().getParcelableExtra("data");
Extend ArrayAdapter and pass your list of contacts in the constructor parameter to it. Assign that list to a field inside ArrayAdapter and then in your getView() method, you can get your item by simple list.get(position).
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.
I read data from json file to an adapter and in the main.java under oncreate, when I try runing it,it doest show anything.
I tried the same code under menu onclick and it works, I want it to appear when the app is first runed.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
String url = "myjsonurl.php";
JSONArray jArray;
ProgressDialog dialog;
ListView mycustomlist = null;
WebView mywebview =null;
CustomAdapter myadapter = null;
ArrayList<news> mydatalist = new ArrayList<news>();
ArrayList<news> maşetData = new ArrayList<news>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myadapter = new CustomAdapter(this, mydatalist);
mycustomlist = (ListView)findViewById(R.id.listview);
mycustomlist.setAdapter(myadapter);
dialog = new ProgressDialog(this);
dialog.setMessage("Loading....");
dialog.show();
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String string) {
parseJsonData(string);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), "Some error occurred!!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
dialog.cancel();
}
});
RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
rQueue.add(request);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/* FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
*/
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public void parseJsonData(final String jsonString) {
try {
jArray = new JSONArray(jsonString);
for(int i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
news news1 = new news();
news1.setTitle(jObject.getString("title"));
news1.setContent(Html.fromHtml(jObject.getString("content")));
news1.setDate(jObject.getString("date"));
news1.setImage("http://www.bolgegundem.com/d/news/" + jObject.getString("image").concat(".jpg"));
news1.setId(jObject.getString("id"));
news1.setCategory(jObject.getString("category"));
news1.set__comment_count(jObject.getString("__comment_count"));
news1.setHeadline(jObject.getString("headline"));
mydatalist.add(news1);
// http://www.bolgegundem.com/d/gallery/81_2.jpg
/* images.add("http://www.bolgegundem.com/d/gallery/" + id + "_" + imgUrl.replace(",", ".jpg") );*/
// al.add(title);
//imagelinks[i] = "http://www.bolgegundem.com/d/gallery/" + id + "_" + i + ".jpg";
}
// ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_activated_1, al);
//listview.setAdapter(adapter);
// listview.setBackgroundColor(rgb(0, 255, 255));
/* listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(i < links.length){
Uri uri = Uri.parse(links[i]);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
});*/
if (dialog.isShowing()){
dialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
dialog.dismiss();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.manşet) {
// Handle the camera action
} else if (id == R.id.Anasayfa) {
myadapter = new CustomAdapter(this, mydatalist);
mycustomlist = (ListView)findViewById(R.id.listview);
mycustomlist.setAdapter(myadapter);
} else if (id == R.id.ajansTv) {
} else if (id == R.id.foto) {
} else if (id == R.id.gundem) {
} else if (id == R.id.siyaset) {
}else if (id ==R.id.Ekonomi ){
}else if (id ==R.id.spor ){
}else if (id ==R.id.saglik ){
}else if (id ==R.id.nav_share ){
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
My adapter class is here
public class CustomAdapter extends BaseAdapter {
Context mycontext = null;
ArrayList<news> mydatalist;
public CustomAdapter(Context mycontext, ArrayList<news> mydatalist)
{
this.mycontext = mycontext;
this.mydatalist = mydatalist;
}
#Override
public int getCount() {
return this.mydatalist.size();
}
#Override
public Object getItem(int position) {
return this.mydatalist.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater myinflater = (LayoutInflater)mycontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewHolder myholder = null;
if(convertView == null)
{
convertView = myinflater.inflate(R.layout.customlayout, null);
myholder = new ViewHolder();
myholder.mytextview1 = (TextView)convertView.findViewById(R.id.mytextview1);
myholder.mytextview2 = (TextView)convertView.findViewById(R.id.mytextview2);
myholder.mytextview3 = (TextView)convertView.findViewById(R.id.mytextview3);
myholder.myimageview1 = (ImageView)convertView.findViewById(R.id.imageView);
convertView.setTag(myholder);
}
else
{
myholder = (ViewHolder)convertView.getTag();
}
myholder.mytextview1.setText(mydatalist.get(position).getTitle());
myholder.mytextview2.setText(mydatalist.get(position).getContent());
myholder.mytextview3.setText(mydatalist.get(position).getDate());
myholder.myimageview1.setImageResource(R.drawable.bolgegundem);
new DownloadImageTask(myholder.myimageview1).execute(mydatalist.get(position).getImage());
return convertView;
}
static class ViewHolder
{
public TextView mytextview1;
public TextView mytextview2;
public TextView mytextview3;
public ImageView myimageview1;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
How can I solve this?
Put the three lines
myadapter = new CustomAdapter(this, mydatalist);
mycustomlist = (ListView)findViewById(R.id.listview);
mycustomlist.setAdapter(myadapter);
in this method:
#Override
public void onResponse(String string) {
parseJsonData(string);
// put them here
}
This will work because it populates the list after the data is parsed add then adds it to the adapter. If you add the list to the adapter in OnCreate, the onResponse method will run later (when the data is returned) and the list will be empty.
you need to create fragments for every item which you declare in navigation and do parsing and all thing in it and that fragment is called from onNavigationItemSelected and if you want which is always show first than you have to call it in also from onCreate() method.
I am trying to pass data into an intent, I have added a onclicklistener method on onCreate(), but for some reason when I press any list view item it is not opening the intent for me. the array list is not on the same class as the main activity.
here is my MainActivity (onCreate) code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new GetRestaurants(places,this,lv).execute();
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ArrayAdapter<Restaurant> adapter = new CustomAdapter(this, 0, places);
ListView listView = (ListView) findViewById(R.id.customListView);
listView.setAdapter(adapter);
AdapterView.OnItemClickListener adapterViewListener = new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Restaurant restaurant = places.get(position);
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("name", restaurant.getName());
startActivity(intent);
}
};
listView.setOnItemClickListener(adapterViewListener);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
my intent activity:
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_layout);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
TextView nameTV = (TextView) findViewById(R.id.name);
Intent intent = getIntent();
String name1= intent.getStringExtra("name");
nameTV.setText(name1);
}}
And here is my custom adapter which gets the restaurant details:
public class CustomAdapter extends ArrayAdapter<Restaurant> {
private Context context;
private List<Restaurant> places;
public CustomAdapter(Context context, int resource, ArrayList<Restaurant> objects) {
super(context, resource, objects);
this.context = context;
this.places = objects;
}
public View getView(int position, View convertView, ViewGroup parent) {
Restaurant restaurant = places.get(position);
//get the inflater and inflate the XML layout for each item
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.search_layout, null);
TextView name = (TextView) view.findViewById(R.id.name);
TextView address1 = (TextView) view.findViewById(R.id.address1);
TextView menu = (TextView) view.findViewById(R.id.menu);
TextView price = (TextView) view.findViewById(R.id.price);
TextView phone = (TextView) view.findViewById(R.id.phone);
TextView rate = (TextView) view.findViewById(R.id.rate);
name.setText("Name " + restaurant.getName());
address1.setText("Address " +restaurant.getAddress1());
menu.setText("Cuisine "+restaurant.getMenu_type());
price.setText("Price " + Integer.toString(restaurant.getCost()));
phone.setText("Phone " +Integer.toString(restaurant.getPhone()));
rate.setText( "Rate " +Float.toString(restaurant.getRate()));
return view;
}}
and here is the error I am getting once I click on any item on the list view after it get populated:
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
com.example.abdulhakim.navbar.MainActivity$1.onItemClick(MainActivity.java:52)
03-05 22:02:53.212 25306-25306/com.example.abdulhakim.navbar
Code for
GetRestaurant
public class GetRestaurants extends AsyncTask<Void, Void, Void> {
private String host ="";
private String port = "";
private String Search="/api/restaurants/search/";
private String getplace="/api/restaurants/search/";
private String register="api/users/add";
private String url = "http://#DELETED#/api/restaurants/search/?key=Burger&col=menu_type";
private String TAG = MainActivity.class.getSimpleName();
private ArrayList<Restaurant>places;
private Context context;
private Dialog dialog;
private ListView lv;
public GetRestaurants(ArrayList<Restaurant> places,Context context,ListView lv) {
this.places = places;
this.context=context;
this.lv=lv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(context,ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(true);
dialog.show();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ArrayAdapter<Restaurant> adapter = new CustomAdapter(context, 0, places);
ListView lv = (ListView) findViewById(R.id.customListView);
lv.setAdapter(adapter);
// Dismiss the progress dialog
if (dialog.isShowing())
dialog.dismiss();
}
protected Void doInBackground(Void... arg0) {
places = new ArrayList<>();
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 restaurants = jsonObj.getJSONArray("restaurants");
// looping through the JSON object
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String address1 = c.getString("address1");
String address2 = c.getString("address2");
String lat = c.getString("lat");
String lng = c.getString("lng");
String cost = c.getString("cost");
String menu_type = c.getString("menu_type");
String rate = c.getString("rate");
String offer = c.getString("offer");
// Phone node is JSON Object
String mobile = c.getString("phone");
places.add(new Restaurant(Integer.parseInt(id),name,address1,address2,Integer.parseInt(mobile)
,Float.parseFloat(lat),Float.parseFloat(lng)
,Integer.parseInt(cost),menu_type,Float.parseFloat(rate),offer));
}
}
catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
}
} else {
Log.e(TAG, "Couldn't get json from server.");
}
return null;
}
}
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");
}
This question already has answers here:
Android - Show a message if no internet connection and continue to check
(2 answers)
Closed 7 years ago.
I want to display an alert message when Internet connection is not available in my android project. My Activity class loads a list-view through Internet and if the devices doesn't have an Internet connection it simply displays the activity. I want to show a toast or a prompt that your device doesn't have Internet connection.
here is my activity class:
public class MainActivity2 extends AppCompatActivity {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
private static final String TAG_TITLE = "title";
private static final String TAG_RATING = "rating";
private Toolbar mToolbar;
private FloatingActionButton fab;
// Movies json url
private static final String url = "http://groupdiscount.netne.net/android_connect/movie.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity2.this, Register.class);
startActivity(intent);
}
});
// Listview on item click listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title))
.getText().toString();
String rating = ((TextView) view.findViewById(R.id.rating))
.getText().toString();
// Starting single activity
Intent in = new Intent(getApplicationContext(),
SingleActivity.class);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_RATING, rating);
startActivity(in);
}
});
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#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;
}
}
public boolean isOnline() {
boolean result;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()){
result=true;
}
else{
Toast.makeText(getBaseContext(), "Not Online",7000).show();
result=false;
}
return result;
}
and use it as following:
if(isOnline()){
loadListView(); // This would be the method that you load listview
}