How to dynamically create buttons from Json string - java

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.

Related

how to go to new activity after clicking an item in the listview?

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

Load JSON arraylist in separate class and load in another activity

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

Android Java dynamic button click

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).

How to improve classes ? Issue with inner classes [Android]

I'm using Android Studio to develop my app. I have two activities that does the same thing (except a parameter value) and I have an inner class inside which does the same thing too in the other activity. My inner class extends AsyncTask for background downloading. But, if I extend my second activity from my 1st activity, I can't do task.execute(), I will need to extend AyncTask too,and extending from two classes impossible in Java.. Here's my code :
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private TextView title;
private List<User> myList;
String query_url;
MyAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recycler = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recycler.setLayoutManager(llm);
//create and execute new task
AsyncDL task = new AsyncDL();
task.execute();
}
//background download
private class AsyncDL extends AsyncTask<Object, String, Integer> {
#Override
protected Integer doInBackground(Object... params) {
tryDownloadXmlData();
return null;
}
private void tryDownloadXmlData() {
try {
URL xmlUrl = new URL(query_url);
myXMLPullParser myCustomParser = new myXMLPullParser();
//fetch & parse data
myList = myCustomParser.parse(xmlUrl.openStream());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(Integer integer) {
myAdapter = new MyAdapter(getApplicationContext(), myList);
recycler.setAdapter(myAdapter);
RecyclerItemClickSupport.addTo(recycler).setOnItemClickListener(new RecyclerItemClickSupport.OnItemClickListener() {
#Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
User user = myList.get(position);
Intent myIntent = new Intent(getApplicationContext(), Details.class);
myIntent.putExtra("user", user);
startActivity(myIntent);
}
});
super.onPostExecute(integer);
}
}
}
I don't really know if it is possible to reuse an activity's code like that, thanks !
EDIT: new piece of code
ProductAsyncTask task = new ProductAsyncTask(getApplicationContext(), listview, QUERY_URL, productList, myCustomAdapter);
task.execute();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
User currentUser = myList.get(position); //error here
Intent myIntent = new Intent(getApplicationContext(), Detail_User.class);
myIntent.putExtra("currentUser", currentUser);
Log.i("INFO", "Loading extra data for transfer...");
startActivity(myIntent);
}
});

want to display an alert when internet connection is not available in android [duplicate]

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
}

Categories