After Clicking an Item in my List view, my Single Item View should appear. Unfortunately every time i click on one of the two items just the same content appears. How can i fix the problem and the right content will be shown?
First i get parse data in my Main Activity:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = MainActivity.class.getSimpleName();
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
int i = 1;
private ProgressDialog pDialog;
String name;
String image;
String street;
String postalcode;
String musicstyle;
String musicsecond;
String entry;
String opening;
String agegroup;
String urlbtn;
String Fsk;
String city;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/maptest.json";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener((AdapterView.OnItemClickListener) this);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
final Button popbutton = (Button) findViewById(R.id.popbutton);
popbutton.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View v) {
if (i == 1) {
if (popbutton.isPressed()) {
popbutton.setBackground(getResources().getDrawable(R.drawable.secondbg));
arrayList.clear();
url = "http://partypeople.bplaced.net/justpop.json";
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
i = i + 1;
}
} else {
if (popbutton.isPressed()) {
popbutton.setBackground(getResources().getDrawable(R.drawable.bg_popbutton));
arrayList.clear();
url = "http://partypeople.bplaced.net/maptest.json";
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
i = i - 1;
}
}
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String>{
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
if (pDialog.isShowing())
pDialog.dismiss();
try{
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
arrayList.add(new productforloc(
image= po.getString("imageurl"),
name = po.getString("name"),
street = po.getString("street"),
postalcode = po.getString("postalcode"),
musicstyle = po.getString("musicstyle"),
musicsecond = po.getString("musicsecond"),
entry = po.getString("entry"),
opening = po.getString("opening"),
agegroup = po.getString("agegroup"),
urlbtn = po.getString("urlbtn"),
Fsk = po.getString("Fsk"),
city = po.getString("city")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
}
}
private String readURL(String url){
StringBuilder content = new StringBuilder();
try{
URL uri = new URL(url);
URLConnection urlConnection = uri.openConnection();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) !=null){
content.append(line+"\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",name);
intent.putExtra("imageurl",image);
intent.putExtra("street",street);
intent.putExtra("postalcode",postalcode);
intent.putExtra("musicstyle",musicstyle);
intent.putExtra("musicsecond",musicsecond);
intent.putExtra("entry",entry);
intent.putExtra("opening",opening);
intent.putExtra("agegroup",agegroup);
intent.putExtra("urlbtn",urlbtn);
intent.putExtra("Fsk",Fsk);
intent.putExtra("city",city);
startActivity(intent);
Toast.makeText(getApplicationContext(),street,Toast.LENGTH_LONG).show();
}
/**
* Async task class to get json by making HTTP call
}
*/
}
Then as you can see in the bottom the content will be sent to the detailactivity, but i always get the content from the second item in my json even if i click on the first item.
Change your onItemClick method to get the right object from your list.
Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(positon);
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",pForloc.getName());
intent.putExtra("imageurl",pForloc.getImage());
intent.putExtra("street",pForloc.getStreet());
intent.putExtra("postalcode",pForloc.getPostalcode());
intent.putExtra("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
startActivity(intent);
Toast.makeText(getApplicationContext(),street,Toast.LENGTH_LONG).show();
}
Related
I am trying to pass a ListView item from a fragment to a String variable "url" in activity, The intent successfully creates the activity however I run issues into it when I try passing data.
the fragment class has a listview with json data that brings up the list of picture,title and name. when a user selects an item it brings them to the activity. I want their selection transfer the name from the listview to the url variable in the other activity. so the url changed from "https://.....id=" to "https://.....id="+name from the fragment.
thats will make the recyclerview changed with the new url for any listview item clicked.
my fragment:
public class Accueil extends Fragment {
ArrayList<articles> arrayList;
ListView lv;
public static String URL1=null;
class ReadJSON extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(content);
} catch (JSONException e1) {
e1.printStackTrace();
}
JSONArray jsonArray = null;
try {
jsonArray = jsonObject.getJSONArray("articles");
} catch (JSONException e1) {
e1.printStackTrace();
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articlesobject = null;
try {
articlesobject = jsonArray.getJSONObject(i);
} catch (JSONException e1) {
e1.printStackTrace();
}
try {
arrayList.add(new articles(
articlesobject.getString("picture"),
articlesobject.getString("title"),
articlesobject.getString("name")
));
} catch (JSONException e1) {
e1.printStackTrace();
}
CustomListAdaper adaper = new CustomListAdaper(
getActivity().getApplicationContext(),
R.layout.custom_list_layout, arrayList
);
lv.setAdapter(adaper);
}
}
private String readURL(String theURL) {
StringBuilder content = new StringBuilder();
try {
URL url = new URL(theURL);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
arrayList = new ArrayList<>();
View rootView = inflater.inflate(R.layout.accueil, container, false);
lv = (ListView) rootView.findViewById(R.id.ListView1);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
new Accueil.ReadJSON().execute("http://wach.ma/mobile/home.php");
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int
position, long id) {
String selectedFromList =
(lv.getItemAtPosition(position).toString());
Intent i = new Intent(getActivity(), Test.class);
i.putExtra("name", selectedFromList);
startActivity(i);
}
});
return rootView;
}
}
my activity:
public class Test extends AppCompatActivity {
public String URL_DATA="http://wach.ma/mobile/category.php?id=";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
Intent i = getIntent();
String s1 = i.getStringExtra("name");
URL_DATA=URL_DATA+s1;
loadRecyclerViewData();
}
private void loadRecyclerViewData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Chargement...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("articles");
for(int i = 0; i<array.length();i++){
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(
o.getString("picture"),
o.getString("name"),
o.getString("city"),
o.getString("add_time"),
o.getString("price")
);
listItems.add(item);
}
adapter = new Myadapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(),
volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Thank you in advance, and i'm very sorry for my bad English
Your problem comes from this I think : String selectedFromList =
(lv.getItemAtPosition(position).toString());
lv.getItemAtPosition(position) returns an Object which is an item of the listView Adapter !
Calling toString() on this object will return nothing good :)
The OnClickListener has a View in parameter which is the parent View, in your case, the Item View you clicked.
You can retrieve the TextView holding the name field in the OnClickListener and get the string of this TextView like this :
#Override
public void onItemClick(AdapterView<?> parent, View view, int postion, long id) {
String name = ((TextView) view.findViewById(R.id.myNameField)).getText().toString();
}
Hope that will help you :)
PS : Post your XML code as well next time ;)
I fix it, just change this:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int
position, long id) {
String selectedFromList =
(lv.getItemAtPosition(position).toString());
Intent i = new Intent(getActivity(), Test.class);
i.putExtra("name", selectedFromList);
startActivity(i);
}
});
return rootView;
to this:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int
position, long id) {
String selectedFromList=
String.valueOf(arrayList.get(position).getIdd());
Intent i = new Intent(getActivity(), Test.class);
i.putExtra("name", selectedFromList);
startActivity(i);
}
});
return rootView;
iam creating an App which should show the Sights in a Listview.
The datas are parsed from a json.
At this json there is a column which declares in which City the sight is.
Now i would like to create a kind of a filter which should check the current Cityname with the City values in my Json.
For example there is a Sight in Berlin and my current city is Berlin, the Listview should show it. If the user is in Munich and the sight is in Berlin, the listview shouldnt show this item.
I get the current cityname value from a different Activity in a TextView.
Here is my Listview Activity:
public class Locations extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = Locations.class.getSimpleName();
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
int i = 1;
private ProgressDialog pDialog;
String name;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/maptest.json";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Intent i = getIntent();
String cityname = i.getExtras().getString("cityname");
TextView city = (TextView) findViewById(R.id.ort);
city.setText(cityname);
pDialog = new ProgressDialog(Locations.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener((AdapterView.OnItemClickListener) this);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
final ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.VISIBLE);
ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setVisibility(View.VISIBLE);
filteropen.setVisibility(View.INVISIBLE);
}
});
final ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.INVISIBLE);
ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setVisibility(View.VISIBLE);
filterclose.setVisibility(View.INVISIBLE);
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try{
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
arrayList.add(new productforloc(
po.getString("imageurl"),
po.getString("name"),
po.getString("street"),
po.getString("postalcode"),
po.getString("musicstyle"),
po.getString("musicsecond"),
po.getString("entry"),
po.getString("opening"),
po.getString("agegroup"),
po.getString("urlbtn"),
po.getString("Fsk"),
po.getString("city"),
po.getString("bg")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
final CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
}
private String readURL(String url){
StringBuilder content = new StringBuilder();
try{
URL uri = new URL(url);
URLConnection urlConnection = uri.openConnection();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) !=null){
content.append(line+"\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(position);
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",pForloc.getName());
intent.putExtra("imageurl",pForloc.getImage());
intent.putExtra("street",pForloc.getStreet());
intent.putExtra("postalcode",pForloc.getPostalcode());
intent.putExtra("entry",pForloc.getEntry());
intent.putExtra("agegroup",pForloc.getAgegroup());
intent.putExtra("opening",pForloc.getOpening());
intent.putExtra("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
intent.putExtra("musicstyle",pForloc.getMusicstyle());
intent.putExtra("musicsecond",pForloc.getMusicsecond());
intent.putExtra("bg",pForloc.getBg());
startActivity(intent);
}
/**
* Async task class to get json by making HTTP call
}
*/
}
and here is my Customlistadapter Activity;
public class CustomListAdapterforloc extends ArrayAdapter<productforloc>{
ArrayList<productforloc> products;
Context context;
int resource;
public CustomListAdapterforloc(Context context, int resource, List<productforloc> products) {
super(context, resource, products);
this.products = (ArrayList<productforloc>) products;
this.context = context;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView== null){
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.model,null,true);
}
productforloc product = getItem(position);
ImageView imageView = (ImageView) convertView.findViewById(R.id.imagelist);
Picasso.with(context).load(product.getImage()).into(imageView);
TextView txtName= (TextView) convertView.findViewById(R.id.namelist);
txtName.setText(product.getName());
return convertView;
}
}
Get current city name from intent.
String currentCityName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Intent i = getIntent();
currentCityName = i.getExtras().getString("cityname");
...........
.................
}
Add condition to match cityName with currentCityName before adding productforloc object to ArrayList:
try {
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
String cityName = po.getString("city");
if(!cityName.equals(currentCityName)) {
arrayList.add(new productforloc(
po.getString("imageurl"),
po.getString("name"),
po.getString("street"),
po.getString("postalcode"),
po.getString("musicstyle"),
po.getString("musicsecond"),
po.getString("entry"),
po.getString("opening"),
po.getString("agegroup"),
po.getString("urlbtn"),
po.getString("Fsk"),
po.getString("city"),
po.getString("bg")));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
im trying to parse data from SQL Database into Listview.
My PHP script is working because if i run it in the browser i get the content.
If im trying to get the data from my SQL Databse into the listview my app shows nothing.
Here is my MainActivity:
public class Locations extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = Locations.class.getSimpleName();
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
int i = 1;
private ProgressDialog pDialog;
String name;
// URL to get contacts JSON
private static String url = "Mylink";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Intent i = getIntent();
String cityname = i.getExtras().getString("cityname");
TextView city = (TextView) findViewById(R.id.ort);
city.setText(cityname);
pDialog = new ProgressDialog(Locations.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener((AdapterView.OnItemClickListener) this);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
final ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.VISIBLE);
ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setVisibility(View.VISIBLE);
filteropen.setVisibility(View.INVISIBLE);
}
});
final ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.INVISIBLE);
ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setVisibility(View.VISIBLE);
filterclose.setVisibility(View.INVISIBLE);
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try{
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
arrayList.add(new productforloc(
po.getString("imageurl"),
po.getString("name"),
po.getString("street"),
po.getString("postalcode"),
po.getString("musicstyle"),
po.getString("musicsecond"),
po.getString("entry"),
po.getString("opening"),
po.getString("agegroup"),
po.getString("urlbtn"),
po.getString("Fsk"),
po.getString("city"),
po.getString("bg")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
final CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
}
private String readURL(String url){
StringBuilder content = new StringBuilder();
try{
URL uri = new URL(url);
URLConnection urlConnection = uri.openConnection();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) !=null){
content.append(line+"\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(position);
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",pForloc.getName());
intent.putExtra("imageurl",pForloc.getImage());
intent.putExtra("street",pForloc.getStreet());
intent.putExtra("postalcode",pForloc.getPostalcode());
intent.putExtra("entry",pForloc.getEntry());
intent.putExtra("agegroup",pForloc.getAgegroup());
intent.putExtra("opening",pForloc.getOpening());
intent.putExtra("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
intent.putExtra("musicstyle",pForloc.getMusicstyle());
intent.putExtra("musicsecond",pForloc.getMusicsecond());
intent.putExtra("bg",pForloc.getBg());
startActivity(intent);
}
/**
* Async task class to get json by making HTTP call
}
*/
}
and here is my Customlistadapter Activity:
public class CustomListAdapterforloc extends ArrayAdapter<productforloc>{
ArrayList<productforloc> products;
Context context;
int resource;
public CustomListAdapterforloc(Context context, int resource, List<productforloc> products) {
super(context, resource, products);
this.products = (ArrayList<productforloc>) products;
this.context = context;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView== null){
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.model,null,true);
}
productforloc product = getItem(position);
ImageView imageView = (ImageView) convertView.findViewById(R.id.imagelist);
Picasso.with(context).load(product.getImage()).into(imageView);
TextView txtName= (TextView) convertView.findViewById(R.id.namelist);
txtName.setText(product.getName());
return convertView;
}
}
i solved it using this code in my MAinActivity:
public class Locations extends AppCompatActivity {
private String TAG = Locations.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/loli.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Locations.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 {
JSONArray contacts = new JSONArray(jsonStr);
// Getting JSON Array node
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
// adding contact to contact list
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();
/**3
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Locations.this, contactList,
R.layout.model, new String[]{"name", "email",
"mobile"}, new int[]{R.id.namelist,
});
lv.setAdapter(adapter);
}
}
and used in my CustomlistadapterActivity:
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Thanks for your input
Override getCount method into adapter class.
I'm having a hard time figuring out how to implement the new MyAsyncTask().execute("") that I've searched because I have separate classes that extends Asynctask. I wanted to call the class everytime i click the button. Hope you guys can help me figure this out.
Here is my MainActivity
public class MainActivity extends AppCompatActivity {
String url = "http://192.168.254.103/dbtest/categories.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.start);
final ListView lv = (ListView) findViewById(R.id.lv);
final Downloader d = new Downloader(this,url,lv);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.execute();
}
});
}
}
Here is my Downloader.java
public class Downloader extends AsyncTask<Void,Integer, String> {
Context c;
String address;
ListView lv;
ProgressDialog pd;
public Downloader(Context c, String address, ListView lv) {
this.c = c;
this.address = address;
this.lv = lv;
}
//BEFORE JOB STARTS
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Fetch Data");
pd.setMessage("Please Wait");
pd.show();
}
#Override
protected String doInBackground(Void... params) {
String data = downloadData();
return data;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
if(s != null){
Parser p =new Parser(c,s,lv);
p.execute();
}else
{
Toast.makeText(c,"Unable to download data",Toast.LENGTH_SHORT).show();
}
}
private String downloadData(){
//connect and get a stream
InputStream is = null;
String line = null;
try{
URL url = new URL(address);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(con.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
if(br != null){
while((line = br.readLine()) != null)
{
sb.append(line+"\n");
}
}
else
{
return null;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
and my Parser.java
public class Parser extends AsyncTask<Void,Integer,Integer> {
Context c;
ListView lv;
String data;
ArrayList<String> categories = new ArrayList<>();
ProgressDialog pd;
public Parser(Context c, String data, ListView lv) {
this.c = c;
this.data = data;
this.lv = lv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Parser");
pd.setMessage("Please Wait");
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parse();
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer == 1)
{
//ADAPTER
ArrayAdapter<String> adapter = new ArrayAdapter<String>(c, android.R.layout.simple_list_item_1, categories);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}else
{
Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
}
pd.dismiss();
}
//PARSE RECEIVED DATA
private int parse(){
try
{
//ADD TGAT DATA TO JSON ARRAY FIRST
JSONArray ja = new JSONArray(data);
//CREATE JO OBJECT TO HOLD A SINGLE ITEM
JSONObject jo = null;
categories.clear();
//LOOP THROUGH ARRAY
for(int i =0 ; i<ja.length();i++)
{
jo = ja.getJSONObject(i);
//RETRIEVE NAME
String name=jo.getString("cat_name");
//ADD TO ARRAY LIST
categories.add(name);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
code which one should I change to throw button and instantly displays my listview without having to click a button
public class MainActivity extends AppCompatActivity {
Button btnLoadFeed; <<<<<------------- Which should I remove associated with this code?
TextView textViewFeedUrl;
ListView listViewFeed;
List<FeedItem> listFeedItems;
ListAdapter adapterFeed;
String myFeed = "http://temfilm.blogspot.co.id/feeds/posts/default?alt=json";
//String myFeed = "http://arduino-er.blogspot.com/feeds/posts/default?alt=json";
//String myFeed = "http://helloraspberrypi.blogspot.com/feeds/posts/default?alt=json";
//String myFeed = "http://photo-er.blogspot.com/feeds/posts/default?alt=json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLoadFeed = (Button)findViewById(R.id.loadfeed);
textViewFeedUrl = (TextView)findViewById(R.id.feedurl);
setContentView(R.layout.layout_feed);
listViewFeed = (ListView)findViewById(R.id.listviewfeed);
listFeedItems = new ArrayList<>();
adapterFeed = new ArrayAdapter<FeedItem>(
this, android.R.layout.simple_list_item_1, listFeedItems);
listViewFeed.setAdapter(adapterFeed);
btnLoadFeed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textViewFeedUrl.setText(myFeed);
new JsonTask(listFeedItems, listViewFeed).execute(myFeed);
}
});
}
/*
JsonTask:
AsyncTask to download and parse JSON Feed of blogspot in background
*/
private class JsonTask extends AsyncTask<String, FeedItem, String> {
List<FeedItem> jsonTaskList;
ListView jsonTaskListView;
public JsonTask(List<FeedItem> targetList, ListView targetListView) {
super();
jsonTaskList = targetList;
jsonTaskListView = targetListView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
jsonTaskList.clear();
jsonTaskListView.invalidateViews();
}
#Override
protected String doInBackground(String... params) {
try {
final String queryResult = sendQuery(params[0]);
parseQueryResult(queryResult);
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
eString,
Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
final String eString = e.toString();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
eString,
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onProgressUpdate(FeedItem... values) {
FeedItem newItem = values[0];
jsonTaskList.add(newItem);
jsonTaskListView.invalidateViews();
}
private String sendQuery(String query) throws IOException {
String queryReturn = "";
URL queryURL = new URL(query);
HttpURLConnection httpURLConnection = (HttpURLConnection)queryURL.openConnection();
if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader inputStreamReader =
new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader, 8192);
String line = null;
while((line = bufferedReader.readLine()) != null){
queryReturn += line;
}
bufferedReader.close();
}
return queryReturn;
}
private void parseQueryResult(String json) throws JSONException {
JSONObject jsonObject = new JSONObject(json);
final JSONObject jsonObject_feed = jsonObject.getJSONObject("feed");
final JSONArray jsonArray_entry = jsonObject_feed.getJSONArray("entry");
runOnUiThread(new Runnable() {
#Override
public void run() {
if(jsonArray_entry == null){
Toast.makeText(MainActivity.this,
"jsonArray_entry == null",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,
String.valueOf(jsonArray_entry.length()),
Toast.LENGTH_LONG).show();
for(int i=0; i<jsonArray_entry.length(); i++){
try {
JSONObject thisEntry = (JSONObject) jsonArray_entry.get(i);
JSONObject thisEntryTitle = thisEntry.getJSONObject("title");
String thisEntryTitleString = thisEntryTitle.getString("$t");
JSONArray jsonArray_EntryLink = thisEntry.getJSONArray("link");
//search for the link element with rel="alternate"
//I assume it's one and only one element with rel="alternate",
//and its href hold the link to the page
for(int j=0; j<jsonArray_EntryLink.length(); j++){
JSONObject thisLink = (JSONObject) jsonArray_EntryLink.get(j);
try{
String thisLinkRel = thisLink.getString("rel");
if(thisLinkRel.equals("alternate")){
try{
String thisLinkHref = thisLink.getString("href");
FeedItem thisElement = new FeedItem(
thisEntryTitleString.toString(),
thisLinkHref);
publishProgress(thisElement);
break;
}catch (JSONException e){
//no such mapping exists
}
}
}catch (JSONException e){
//no such mapping exists
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
});
}
}
}