I am building a search app using fragments for each screen. I have the search working and storing the JSON results in an ArrayList<Map<String, String>>in the main activity so the other fragments can access it. the current problem is on my resultsFragment I have a Google MapFragment embedded in the main ListFragment and a listView below that. The map is successfully populated, but the list is empty. I have spent hours trying to figure this out. Here is the code for resultsFragment
package com.wny.wecare.fragment;
import java.util.ArrayList;
import java.util.Map;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.wny.wecare.MainActivity;
import com.wny.wecare.R;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ResultsFragment extends ListFragment {
ArrayList<Map<String, String>> resultsList = new ArrayList<Map<String, String>>();
private GoogleMap map;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_results, container, false);
//Get search results from stored ArrayList
resultsList = MainActivity.getResultsList();
//Build listView from results
ListView lv =(ListView) getActivity().findViewById(android.R.id.list);
ListAdapter adapter = new SimpleAdapter(getActivity(), resultsList,
R.layout.custom_row_view, new String[] { "AgencyID", "AgencyName",
"Address1" }, new int[] { R.id.text1, R.id.text2,
R.id.text3 });
// updating listview
setListAdapter(adapter);
//Setup embedded Google Map fragment
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Add markers to the map from resultsList
for (int i = 0; i < resultsList.size(); i++) {
Double latitude = Double.valueOf(resultsList.get(i).get("Lat"));
Double longitude = Double.valueOf(resultsList.get(i).get("Lng"));
String mname = resultsList.get(i).get("AgencyName");
LatLng posit = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions()
.position(posit)
.title(mname));
}
return rootView;
}
}
In case its helpful here is the code from my homeFragment (where the search results are stored to the ArrayList)
package com.wny.wecare.fragment;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.wny.wecare.MainActivity;
import com.wny.wecare.R;
import com.wny.wecare.handler.JSONParser;
public class HomeFragment extends Fragment implements OnItemSelectedListener, OnClickListener{
private OnFragmentInteractionListener mListener;
private Spinner spinner;
private Button btnSubmit;
private static final String[] list={"Alden", "Amherst", "Angola",
"Blasdell", "Boston", "Bowmansville", "Buffalo", "Cheektowaga", "Clarence",
"Depew", "Derby", "East Aurora", "Eden", "Elma", "Getzville", "Gowanda",
"Grand Island", "Holland", "Irving", "Kenmore", "Lackawanna", "Lake View",
"Lancaster", "Lawtons", "North Collins", "Orchard Park", "Snyder", "Springville",
"Tonawanda", "West Seneca", "Williamsville"};
// Setup ArrayList from main activity to store results
ArrayList<Map<String, String>> resultsList = new ArrayList<Map<String, String>>();
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// products JSONArray
JSONArray agency = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
btnSubmit = (Button) rootView.findViewById(R.id.town_search);
btnSubmit.setOnClickListener(this);
spinner =(Spinner)rootView.findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
return rootView;
}
// Check if parent activity implements the interface
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener =
(OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
//add items into spinner dynamically
/*public void addItemsOnSpinner2(View v) {
addItemsOnSpinner2(v);
final List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}*/
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.town_search:
String town = (String) spinner.getSelectedItem().toString();
agencySearch(town);
mListener.onFragmentButton();
break;
case R.id.zip_search:
String strZip = ((EditText) v.findViewById(R.id.txt_zip)).getText().toString().trim();
int zip = Integer.parseInt(strZip);
agencySearch(zip);
mListener.onFragmentButton();
break;
/*case R.id.btn_location:
String strZip = v.findViewById(R.id.txt_zip).toString();
int zip = Integer.parseInt(strZip);
agencySearch(zip);
mListener.onFragmentButton();
break;*/
}
}
#Override
public void onItemSelected(AdapterView<?> parent,
View v, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
public void agencySearch(String tsearch) {
// Setting the URL for the Search by Town
String url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_city.php";
// Building parameters for the search
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("City", tsearch));
// Getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url_search_agency, params);
for (int i = 0; i < json.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
try {
JSONObject c = (JSONObject) json.get(i);
//Fill map
Iterator iter = c.keys();
while(iter.hasNext()) {
String currentKey = (String) iter.next();
map.put(currentKey, c.getString(currentKey));
}
resultsList.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
};
MainActivity.setResultsList(resultsList);
}
public void agencySearch(int zsearch) {
// Setting the URL for the Search by Zip
String url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_zip.php";
// Building parameters for the search
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("zip", Integer.toString(zsearch)));
// Getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url_search_agency, params);
for (int i = 0; i < json.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
try {
JSONObject c = (JSONObject) json.get(i);
//Fill map
Iterator iter = c.keys();
while(iter.hasNext()) {
String currentKey = (String) iter.next();
map.put(currentKey, c.getString(currentKey));
}
resultsList.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
};
MainActivity.setResultsList(resultsList);
}
}
Related
I am new to Java so please excuse any silly or obvious mistake. I have a activity that pulls a json encoded string from a PHP file and put it into a simple list view. I am getting the dreaded red squiggly lines and what is to me a cryptic error message. Here is my code. I appreciate any assistance.
package --Hidden--;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class tracklist extends Activity implements OnItemClickListener {
private static final String URL = "http://rickthompson.com/json/fetchtracks.php";
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracklist);
lv = (ListView) findViewById(R.id.displayTrackList);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
R.layout.rowlayout, R.id.label, profileUserOptions);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
Bundle bundle = getIntent().getExtras();
final String selectedSubGenre = bundle.getString("option");
///////////// login script
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.names().get(0).equals("tracks")) {
Toast.makeText(getApplicationContext(), "tracks " + jsonObject.getString("tracks"), Toast.LENGTH_LONG).show();
/// save user id in prefs
JSONArray contacts = jsonObject.getJSONArray("tracks");
HashMap<String, String> trackview = null;
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String isrc = c.getString("isrc");
trackview = new HashMap<>();
trackview.put("isrc", isrc);
}
trackview.toString();
lv = (ListView) findViewById(R.id.displayTrackList);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.rowlayout, R.id.label, trackview);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
} else {
Toast.makeText(getApplicationContext(), "Error" + jsonObject.getString("error"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<>();
SharedPreferences userPrefs = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
String userid = userPrefs.getString("memberid", "");
hashMap.put("u", userid);
Bundle bundle = getIntent().getExtras();
final String selectedSubGenre = bundle.getString("option");
hashMap.put("sg", selectedSubGenre);
return hashMap;
}
};
requestQueue.add(request);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "something clicked", Toast.LENGTH_LONG).show();
}
}
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.names().get(0).equals("tracks")){
//rest of the code
}
In the above code I hope you are trying to get "name" array which should be
JSONArray jso3 = new JSONArray (jsonObject.getString("names"));
Please provide the error details so that i can give you a detailed description.
I ran into a problem that I can not have any way to solve. I hope you will understand me better.
My code
GuideFragment.java
package ru.yktdevelopers.childrensofasia;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import ru.yktdevelopers.childrensofasia.Download_data.download_complete;
public class GuideFragment extends Fragment implements download_complete {
public ListView list;
public ArrayList<Countries> countries = new ArrayList<Countries>();
public ListAdapter adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.guide_fragment, null);
list = (ListView) v.findViewById(R.id.list_guide);
adapter = new ListAdapter(this);
list.setAdapter(adapter);
Download_data download_data = new Download_data((download_complete) this);
download_data.download_data_from_link("http://9142218380.myjino.ru/testfile.json");
return v;
}
public void get_data(String data)
{
try {
JSONArray data_array=new JSONArray(data);
for (int i = 0 ; i < data_array.length() ; i++)
{
JSONObject obj=new JSONObject(data_array.get(i).toString());
Countries add=new Countries();
add.name = obj.getString("country");
add.code = obj.getString("code");
countries.add(add);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
public class Countries {
String name;
String code;
}
}
The problem is:
How to make so that she was able to open the object with the name "Test".
JSON File located with http://9142218380.myjino.ru/testfile.json
replace it with your functions first line after try
JSONArray data_array=new JSONArray(new JsonObject(data).getJsonArray("Test"));
and pass your whole data from server as string
package com.supdeco.oussamaniba.loginapp;
import android.content.ClipData;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class DisplayListView extends AppCompatActivity {
String JSON_STRING;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;
TextView lstv;
String username,email,password,name,last;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_listview_layout);
listView = (ListView) findViewById(R.id.list);
lstv = (TextView) findViewById(R.id.lstv);
contactAdapter = new ContactAdapter(this, R.layout.row_layout);
listView.setAdapter(contactAdapter);
JSON_STRING = getIntent().getExtras().getString("json_data");
try {
jsonObject = new JSONObject(JSON_STRING);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
username = JO.getString("username");
email = JO.getString("email");
password = JO.getString("password");
name = JO.getString("name");
last = JO.getString("lastname");
Contacts contacts = new Contacts(username,email,password,name,last);
contactAdapter.add(contacts);
count++;
lstv.setText("Available: " + count + " members");
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id)
{
Intent intent = new Intent(getApplicationContext(), SingleUser.class);
intent.putExtra("username", String.valueOf(listView.getSelectedItem()));
startActivity(intent);
}
});
}
}
I try to pass data from this ListView to another EditText in an other
activity but the result is always null, I want to pass all the text
string from the ListView to the EditText.
Do this way,
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id)
{
Intent intent = new Intent(getApplicationContext(), SingleUser.class);
intent.putExtra("username", YourModels.get(position).getUsername());//here first get position and than pass data you want to pass
intent.putExtra("fk_Code", "" + YourModels.get(position).getFk_Code());//take data from your model
startActivity(intent);
}
});
Check this link for more information.
It was too simple i found a simple solution i created a bunch of
string arrays that contains each of the data fetched from the DB and
stored in them, so now i can choose from those String arrays by
position, but thanks anyway
package com.supdeco.oussamaniba.loginapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class DisplayListView extends AppCompatActivity {
String JSON_STRING;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;
TextView lstv;
String username,email,password,name,last;
List<String> susername = new ArrayList<String>();
List<String> sname = new ArrayList<String>();
List<String> slname = new ArrayList<String>();
List<String> spassword = new ArrayList<String>();
List<String> semail = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_listview_layout);
listView = (ListView) findViewById(R.id.list);
lstv = (TextView) findViewById(R.id.lstv);
contactAdapter = new ContactAdapter(this, R.layout.row_layout);
listView.setAdapter(contactAdapter);
JSON_STRING = getIntent().getExtras().getString("json_data");
try {
jsonObject = new JSONObject(JSON_STRING);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
username = JO.getString("username");
email = JO.getString("email");
password = JO.getString("password");
name = JO.getString("name");
last = JO.getString("lastname");
Contacts contacts = new Contacts(username,email,password,name,last);
contactAdapter.add(contacts);
count++;
susername.add(username);
sname.add(name);
slname.add(last);
spassword.add(password);
semail.add(email);
lstv.setText("Available: " + count + " members");
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id)
{
Intent intent = new Intent(getApplicationContext(), SingleUser.class);
String[] N = new String[sname.size()];
N = sname.toArray(N);
String[] L = new String[slname.size()];
L = slname.toArray(L);
String[] U = new String[susername.size()];
U = susername.toArray(U);
String[] P = new String[spassword.size()];
P = spassword.toArray(P);
String[] E = new String[semail.size()];
E = semail.toArray(E);
intent.putExtra("name", N[position]);
intent.putExtra("last", L[position]);
intent.putExtra("username", U[position]);
intent.putExtra("password", P[position]);
intent.putExtra("email", E[position]);
startActivity(intent);
}
});
}
}
I need help from anyone.. please respect my question..
ok, my problem is i want to use Glide for my listview but i dont know to do..
please constract my listviewadapter so that the Glide will work give me any other possible solution to achieve my goal..
my goal is i just want to display image and text in listview or gridview with Glide and JSON, the JSON result is from my php script..
here is my code..
CategoryFragment.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ListView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by Administrator on 9/18/2015.
*/
public class CategoryFragment extends Fragment {
public static CategoryFragment newInstance(String id,String name) {
CategoryFragment fragment = new CategoryFragment();
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("name", name);
fragment.setArguments(bundle);
return fragment;
}
public CategoryFragment () {
}
EditText tpid, tpname;
String cid;
String cname;
String myJSON;
JSONObject jsonobject;
JSONArray jsonarray;
ListView productlistview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
public static String products_id = "products_id";
public static String products_name = "products_name";
public static String products_price = "products_price";
public static String products_image = "products_image";
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.categorylayout, container, false);
getActivity().invalidateOptionsMenu();
tpid = (EditText) rootView.findViewById(R.id.tpid);
tpname = (EditText) rootView.findViewById(R.id.tpname);
if(getArguments() != null) {
String catid = getArguments().getString("id");
String catname = getArguments().getString("name");
tpid.setText(catid);
tpname.setText(catname);
cid = catid;
cname = catname;
}
productlistview = (ListView) rootView.findViewById(R.id.productlistview);
//new DownloadJSON().execute();
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
getProduct();
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
return rootView;
}
public void getProduct(){
class DownloadJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle(cname);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
try {
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(myJSON);
jsonarray = jsonObj.getJSONArray("products");
arraylist = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject p = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("products_id", p.getString("products_id"));
map.put("products_name", p.getString("products_name"));
map.put("products_price", p.getString("products_price"));
map.put("products_image", p.getString("products_image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
adapter = new ListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
productlistview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
DownloadJSON g = new DownloadJSON();
g.execute();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
ListViewAdapter.java
package com.example.administrator.mosbeau;
/**
* Created by Administrator on 9/28/2015.
*/
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import com.bumptech.glide.Glide;
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView products_id;
TextView products_name;
TextView products_price;
ImageView products_image;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.product_listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in product_listview_item.xml
products_id = (TextView) itemView.findViewById(R.id.products_id);
products_name = (TextView) itemView.findViewById(R.id.products_name);
products_price = (TextView) itemView.findViewById(R.id.products_price);
// Locate the ImageView in product_listview_item.xml
products_image = (ImageView) itemView.findViewById(R.id.products_image);
// Capture position and set results to the TextViews
products_id.setText(resultp.get(CategoryFragment.products_id));
products_name.setText(resultp.get(CategoryFragment.products_name));
products_price.setText(resultp.get(CategoryFragment.products_price));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(CategoryFragment.products_image), products_image);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("products_id", resultp.get(CategoryFragment.products_id));
// Pass all data country
intent.putExtra("products_name", resultp.get(CategoryFragment.products_name));
// Pass all data population
intent.putExtra("products_price",resultp.get(CategoryFragment.products_price));
// Pass all data flag
intent.putExtra("products_image", resultp.get(CategoryFragment.products_image));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
Just use : Glide.with(context)
.load(resultp.get(CategoryFragment.products_image))
.into(products_image);
in place of
imageLoader.DisplayImage(resultp.get(CategoryFragment.products_image), products_image);
in your ListViewAdapter.java
I need to do one agenda about some events. I have one list view with all titles about the events for this I use json and mysql for this .
The problem is I am new on android , and I dont know how to do when I click one event title have on Activity with information about this event.
I have the information on database . Can you help me? I need this doing automatically .
My code now is this :
package com.eu.agendamarinhagrande;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.eu.agendamarinhagrande.JSONParser;
import com.eu.agendamarinhagrande.R;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;
public class MainActivity extends ActionBarActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
// JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> empresaList;
// url to get all products list
private static String url_all_empresas = "http://www.grifin.pt/projectoamg/Conexao.php";
// JSON Node names
private static final String TAG_TITULO = "Titulo";
// products JSONArray
String resultado = null;
ListView lista;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Hashmap para el ListView
empresaList = new ArrayList<HashMap<String, String>>();
new Download().execute();
// Cargar los productos en el Background Thread
lista = (ListView) findViewById(R.id.listView);
// ActionBar actionBar = getSupportActionBar();
// actionBar.setDisplayHomeAsUpEnabled(true);
}//fin onCreate
public class Download extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String out = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
final HttpParams httpParameters = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpGet httpPost = new HttpGet(url_all_empresas);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
out = EntityUtils.toString(httpEntity, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return out;
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ArrayList<String> list = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsa = jsonArray.getJSONObject(i);
String str = jsa.getString("Titulo");
String data = jsa.getString("Datainicio");
Log.e("TAG", str);
Log.e("TAG", data);
String s1 = Normalizer.normalize(str, Normalizer.Form.NFKD);
String regex = Pattern.quote("[\\p{InCombiningDiacriticalMarks}\\p{IsLm}\\p{IsSk}]+");
str = new String(s1.replaceAll(regex, "").getBytes("ascii"), "ascii");
list.add(str+"\n"+data);
}
ArrayAdapter adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, list);
// updating listview
//setListAdapter(adapter);
lista.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Some information for you understand my code is portuguese so I translate for you
Titulo-- Title
Data---Date
Descricao---Information about event
Id_evento---Id_event
Imagem---image
You have to add an onItemClickListener to you listview.
mylistview.setOnItemClickListener(this);
where this is your activity`s instance. Make sure please, you activity is implementing the onItemClickListener interface.
public class MainActivity extends Activity implements onItemClickListener{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
listView= ((ListView) findViewById (R.id.list));
listView.setOnItemClickListener (this);
empresaList = new ArrayList<HashMap<String, String>>();
new Download().execute();
//download data to empresaList arrayList , and on PostExeCutre
// create a new adapter with it
// set it to list
}
public void onItemClick (AdapterView<?> parent, View view, int position, long id)
{
//do what you want in your code.
}
}
A long, but good example about onClickListeners:
http://www.mkyong.com/android/android-listview-example/