This question already has answers here:
Passing JSONObject into another activity
(7 answers)
How to pass JSON Object to new activity [duplicate]
(3 answers)
Closed 5 years ago.
I have this class (TodosOsPaises) where I get the data from json and I want to show images from the JSON in the listView for that I'm using a custom adapter (MyAdapter) and on it picasso. The problem is I can't access the "URL_IMAGEM" in the MyAdapter class
TodosOsPaises class:
public class TodosOsPaises extends AppCompatActivity{
private String TAG = TodosOsPaises.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
private static String url = "http://**********/api/continent/any/country/all?id=siF1uXXEsltXOi5CWlSIzy7EABlnE5iF33bnNmfAHJiYXYNmjY";
ArrayList<HashMap<String, String>> listaPaises;
public String URL_IMAGEM;
String Designacao;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todos_os_paises);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("PaĆses");
listaPaises = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetPaises().execute();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
menu.findItem(R.id.spinner_cat).setVisible(false);
menu.findItem(R.id.spinner_pais).setVisible(false);
return true;
}
private class GetPaises extends AsyncTask<Void, Void, Void> implements Serializable {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TodosOsPaises.this);
pDialog.setMessage("Aguarde...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
HttpHandler sh = new HttpHandler();
final String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from URL: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
JSONArray paises = jsonObject.optJSONArray("paises");
if (paises != null) {
for (int j = 0; j < paises.length(); j++) {
JSONObject jsonObject1 = paises.getJSONObject(j);
String K_PAIS = jsonObject1.getString("K_PAIS");
Designacao = jsonObject1.getString("Designacao");
//String URL_IMAGE_SMALL = jsonObject1.getString("URL_IMAGE_SMALL");
URL_IMAGEM = ("http://**********t" + jsonObject1.getString("URL_IMAGE_SMALL")).toString();
String Coord_LAT = jsonObject1.getString("Coord_LAT");
String Coord_LONG = jsonObject1.getString("Coord_LONG");
String Coord_Zoom = jsonObject1.getString("Coord_Zoom");
HashMap<String, String> pais = new HashMap<>();
pais.put("K_PAIS", K_PAIS);
pais.put("Designacao", Designacao);
//pais.put("URL_IMAGE_SMALL", URL_IMAGE_SMALL);
pais.put("URL_IMAGEM", URL_IMAGEM);
pais.put("Coord_LAT", Coord_LAT);
pais.put("Coord_LONG", Coord_LONG);
pais.put("Coord_Zoom", Coord_Zoom);
listaPaises.add(pais);
}
}
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsin 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 errpr!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
ListView list= (ListView) (TodosOsPaises.this).findViewById(R.id.list);
ListAdapter adapter =
new MyAdapter(
(TodosOsPaises.this),
listaPaises,
R.layout.list_item,
new String[]{Designacao},
new int[]{R.id.Designacao});
list.setAdapter(adapter);
/*ListAdapter adapter = new SimpleAdapter(
TodosOsPaises.this,
listaPaises,
R.layout.list_item,
new String[]{"Designacao", },
new int[]{R.id.Designacao, });
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> pare, View view, int position, long id) {
Intent intent = new Intent(TodosOsPaises.this, MapsActivity.class);
intent.putExtra("data", listaPaises.get(position));
startActivity(intent);
}
});*/
Collections.sort(listaPaises, new Comparator<HashMap<String, String>>() {
#Override
public int compare(HashMap<String, String> first, HashMap<String, String> second) {
String firstValue = first.get("Designacao");
String secondValue = second.get("Designacao");
return firstValue.compareTo(secondValue);
}
});
}
}
}
MyAdapter class:
public class MyAdapter extends SimpleAdapter {
public MyAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
public View getView(int position, View convertView, ViewGroup parent){
View v = super.getView(position, convertView, parent);
ImageView img = (ImageView) v.getTag();
if (img == null){
img = (ImageView) v.findViewById(R.id.imageView7);
v.setTag(img);
}
String imageFlag = (String) ((Map)getItem(position)).get(URL_IMAGEM); <<-- here it says "Cannot resolve symbol 'URL_IMAGEM'"
Picasso.with(v.getContext()).load(imageFlag).into(img);
return v;
}
}
That happens, because I don't have URL_IMAGEM defined, I think I need to get it from the TodosOsPaises.
I'm a beginner in android so I'm sorry if I made something wrong
String imageFlag = (String) ((Map)getItem(position)).get("URL_IMAGEM");
thats because their is no string varible of that name in your adapter.You have to supply the string name itseld
Related
I am trying to get JSON data to app, but getting JSON Exception
MainActivity
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private List<Project> projects = new ArrayList<>();
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listView);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading....");
progressDialog.setCancelable(false);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
}
});
Button mFilterButton = (Button) findViewById(R.id.filter_button);
mFilterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this,v);
popupMenu.inflate(R.menu.filter_menu);
popupMenu.show();
}
});
Button mSortButton = (Button) findViewById(R.id.sort_button);
mSortButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this,v);
popupMenu.inflate(R.menu.sort_menu);
popupMenu.show();
}
});
new GSONExecution().execute();
}
private class GSONExecution extends AsyncTask<Void, Void, Boolean>{
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
String urlString = "http://starlord.hackerearth.com/kickstarter";
try {
URL url = new URL(urlString);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("GET");
int res = httpURLConnection.getResponseCode();
if (res == 200){
InputStream inputStream = httpURLConnection.getInputStream();
String s = convertStreamToString(inputStream);
Log.v("Response :" , " is "+ s);
JSONObject rootObject = new JSONObject(s);
JSONArray jsonArray = rootObject.getJSONArray("");
for (int i=0; i<=jsonArray.length(); i++){
JSONObject contactObject = jsonArray.getJSONObject(i);
String titleValue = contactObject.getString("title");
Integer pledgedValue = contactObject.getInt("amt.pledged");
Integer backersValue = contactObject.getInt("num.backers");
Project project = new Project();
project.setPleadges(pledgedValue);
project.setBackers(backersValue);
project.settitle(titleValue);
projects.add(project);
Log.v("Object details : " , " : " + pledgedValue + " : " + backersValue);
}
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean isOperationCompleted) {
super.onPostExecute(isOperationCompleted);
if (isOperationCompleted){
if (progressDialog.isShowing()){
progressDialog.dismiss();
}
ProjectAdapter adapter = new ProjectAdapter(MainActivity.this, projects);
mListView.setAdapter(adapter);
}
}
#NonNull
private String convertStreamToString(InputStream inputStream) {
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"),8);
String line;
while ((line = bufferedReader.readLine()) != null)
stringBuilder.append(line).append("\n");
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
}
}
Project
public class Project {
String mtitle;
Integer mPleadges;
Integer mBackers;
String mNoDays;
public String gettitle() {
return mtitle;
}
public void settitle(String mtitle) {
this.mtitle = mtitle;
}
public Integer getPleadges() {
return mPleadges;
}
public void setPleadges(Integer mPleadges) {
this.mPleadges = mPleadges;
}
public Integer getBackers() {
return mBackers;
}
public void setBackers(Integer mBackers) {
this.mBackers = mBackers;
}
public String getNoDays() {
return mNoDays;
}
public void setNoDays(String mNoDays) {
this.mNoDays = mNoDays;
}
}
ProjectAdapter
class ProjectAdapter extends BaseAdapter{
private List<Project> mList;
private Context mContext;
public ProjectAdapter(MainActivity mainActivity, List<Project> projects) {
this.mList = projects;
this.mContext = mainActivity;
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.project_details,null,false);
final TextView projectName = (TextView) convertView.findViewById(R.id.projectName);
TextView pleadge = (TextView) convertView.findViewById(R.id.pledges);
TextView backers = (TextView) convertView.findViewById(R.id.backers);
projectName.setText(mList.get(position).gettitle());
pleadge.setText(mList.get(position).getPleadges());
backers.setText(mList.get(position).getBackers());
return convertView;
}
}
I am getting org.json.JSONException: Value
at org.json.JSON.typeMismatch(JSON.java:111)
I hope you understand problem, I am still in learning stage so please give brief answer so that i can understand.
You are getting JSONArray from Response and trying to hold on JSONObject which causes org.json.JSONException: Value at org.json.JSON.typeMismatch(JSON.java:111) error
Try this
try {
JSONArray jsonArrayLST = new JSONArray(s);
for (int i = 0; i < jsonArrayLST.length(); i++) {
JSONObject contactObject= jsonArrayLST.getJSONObject(i);
String titleValue = contactObject.getString("title");
Integer pledgedValue = contactObject.getInt("amt.pledged");
Integer backersValue = contactObject.getInt("num.backers");
Project project = new Project();
project.setPleadges(pledgedValue);
project.setBackers(backersValue);
project.settitle(titleValue);
projects.add(project);
Log.v("Object details : " , " : " + pledgedValue + " : " + backersValue);
}
} catch (JSONException e) {
e.printStackTrace();
}
Also, you need to change in your adapter while setting item to textview, because your are setting int value which causes you android.content.res.Resources$NotFoundException: String resource ID error
pleadge.setText(String.valueOf(mList.get(position).getPleadges()));
backers.setText(String.valueOf(mList.get(position).getBackers()));
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();
}
I developed a search function and it worked successfully. The class responsible for the search is called from onQueryTextSubmit and there was nothing wrong with it.
Now I wanted to add other thing that is a button in the same activity of the search bar that when it's clicked all data from the database is displayed in cardView. When I added the code the onQueryTextSubmit method is no longer working plus the button isn't displaying the data. I do not know where is the problem. Here is the code for the whole activity.
PS: for some reason it says that showdata() method is never used.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.find_skill);
button = (Button) findViewById(R.id.button);
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewer);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listView = (ListView) findViewById(R.id.searchList);
searchView = (SearchView) findViewById(R.id.searchView);
noData = (ImageView) findViewById(R.id.nodata);
noNetwork = (ImageView) findViewById(R.id.nonetwork);
urlAdress = "http://skillsexchangecyprus.com/SEC/ss.php";
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
getData();
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
SenderReceiver sr = new SenderReceiver(FindSkill.this, urlAdress,listView, query,noData,noNetwork);
sr.execute();
return false;
}
#Override
public boolean onQueryTextChange(String query) {
return false;
}});}
private void getData() {
class GetData extends AsyncTask<Void, Void, String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(FindSkill.this, "Fetching Data", "Please wait...", false, false);
}
#Override
protected void onPostExecute(String res) {
super.onPostExecute(res);
progressDialog.dismiss();
parseJSON(res);
}
#Override
protected String doInBackground(Void... params) {
BufferedReader bufferedReader = null;
try {
URL url = new URL(Config.GET_URL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetData gd = new GetData();
gd.execute();
}
public void showData(){
adapter = new CardAdapter(Config.skills,Config.ids);
recyclerView.setAdapter(adapter);
}
private void parseJSON(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray array = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
config = new Config(array.length());
for (int i = 0; i < array.length(); i++) {
JSONObject j = array.getJSONObject(i);
Config.skills[i] = getSkill(j);
Config.ids[i] = getId(j);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private String getSkill(JSONObject j){
String name = null;
try {
name = j.getString(Config.JSON_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
private String getId(JSONObject j){
String id = null;
try {
id = j.getString(Config.JSON_ID);
} catch (JSONException e) {
e.printStackTrace();
}
return id;
}
This is the Config class:
public class Config {
public static String[] skills;
public static String[] ids;
public static final String GET_URL = "http://skillsexchangecyprus.com/SEC/mainList.php";
public static final String JSON_ID = "id";
public static final String JSON_NAME = "skill";
public static final String TAG_JSON_ARRAY="result";
public Config(int i) {
skills = new String[i];
ids = new String[i];
}
}
Card Adapter class:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
List<ListItem> items;
public CardAdapter(String[] skills, String[] ids){
super();
items = new ArrayList<>();
for(int i =0; i<items.size(); i++){
ListItem item = new ListItem();
item.setSkill(skills[i]);
item.setId(ids[i]);
items.add(item);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ListItem myAdapter = items.get(position);
holder.skillName.setText(myAdapter.getSkill());
holder.skillId.setText(String.valueOf(myAdapter.getId()));
}
#Override
public int getItemCount() {
return items.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView skillId;
public TextView skillName;
public ViewHolder(View itemView) {
super(itemView);
skillId = (TextView) itemView.findViewById(R.id.skillId);
skillName = (TextView) itemView.findViewById(R.id.skillName);
}
}
}
You did't call your showData() method. You need to create an instance of CardAdapter and set this adapter to your recyclerView.
Update OnCreate() method as below:
..............
....................
urlAdress = "http://skillsexchangecyprus.com/SEC/ss.php";
config = new Config(INITIAL_VALUE);
// Adapter
adapter = new CardAdapter(config.skills,config.ids);
recyclerView.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
getData();
}
});
....................
..............................
Use adapter.notifyDataSetChanged() to update recyclerView with new items.
Update parseJson() method as below:
private void parseJSON(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray array = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
config = new Config(array.length());
for (int i = 0; i < array.length(); i++) {
JSONObject j = array.getJSONObject(i);
config.skills[i] = getSkill(j);
config.ids[i] = getId(j);
// Update
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
In your CardAdapter constructor, use skills.length instead of items.size()
public CardAdapter(String[] skills, String[] ids){
super();
items = new ArrayList<>();
for(int i = 0; i < skills.length; i++){
ListItem item = new ListItem();
item.setSkill(skills[i]);
item.setId(ids[i]);
items.add(item);
}
}
Hope this will work~
I've currently got an application that pulls data from a mysql database and displays it in raw JSON format. I'm currently working on pushing this data into a String variable and displaying it on a Listview on a specific activity.
Problem is, when trying to display this data, my Listview is not populating; I'm sure the variable is not empty as the if statement would have captured this.
Here is snippet of MainActivity code:
//Methods to grab information from abhandym_DB database
public void getJSON(View view){
new BackgroundTask().execute();
}
public void parseJSON(View view){
if(JSON_String==null){
Toast.makeText(getApplicationContext(), "First Get Json", Toast.LENGTH_LONG).show();
}else{
Intent intent = new Intent(this,Test.class);
intent.putExtra("JSON_Data",JSON_String);
startActivity(intent);
}
}
class BackgroundTask extends AsyncTask<Void,Void,String>{
String json_url;
#Override
protected void onPreExecute() {
json_url = "http://abhandyman.x10host.com/json_get_data.php";
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputSteam = httpURLConnection.getInputStream();
BufferedReader buffereredReader = new BufferedReader(new InputStreamReader(inputSteam));
StringBuilder stringBuilder = new StringBuilder();
while((JSON_String = buffereredReader.readLine())!=null){
stringBuilder.append(JSON_String+"\n");
}
buffereredReader.close();
inputSteam.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
TextView textView = (TextView)findViewById(R.id.fragment1_textview_JSONAPPEAR);
textView.setText(result);
JSON_String = result;
}
}
Here is the code for my Test.java
public class Test extends AppCompatActivity {
String JSON_String;
JSONObject jsonObject;
JSONArray jsonArray;
DataAdapter dataAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
listView = (ListView)findViewById(R.id.test_listView);
dataAdapter = new DataAdapter(this, R.layout.row_layout);
listView.setAdapter(dataAdapter);
JSON_String = getIntent().getExtras().getString("JSON_Data");
try {
jsonObject = new JSONObject(JSON_String);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String jobid,problem,resolution;
while(count<jsonObject.length()){
JSONObject JO = jsonArray.getJSONObject(count);
jobid = JO.getString("jobid");
problem = JO.getString("problem");
resolution = JO.getString("resolution");
Data data = new Data(jobid,problem,resolution);
dataAdapter.add(data);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here is the code for my DataAdapter:
public class DataAdapter extends ArrayAdapter{
List list = new ArrayList();
public DataAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Data object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
DataHolder dataHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
dataHolder = new DataHolder();
dataHolder.tx_jobid = (TextView) row.findViewById(R.id.tx_jobid);
dataHolder.tx_problem = (TextView) row.findViewById(R.id.tx_problem);
dataHolder.tx_resolution = (TextView) row.findViewById(R.id.tx_resolution);
row.setTag(dataHolder);
}else{
dataHolder = (DataHolder)row.getTag();
}
Data data = (Data)this.getItem(position);
dataHolder.tx_jobid.setText(data.getJobid());
dataHolder.tx_problem.setText(data.getProblem());
dataHolder.tx_resolution.setText(data.getResolution());
return row;
}
static class DataHolder{
TextView tx_jobid,tx_problem,tx_resolution;
}
}
and here is what it displays when clicking on "Parse JSON" button.
listView empty after population
Any help or advise on why its not displaying would be much appreciated!
Thanks in advance!
your problem seems to be here :
while(count<jsonObject.length()){
you're not looping using the number of array elements but using the number of mapped key:value object which is one (the "server_response") , you have to change this line to :
while(count<jsonArray.length()){
,
you have just the first element showing because jsonObject.length() will return 1 since it have just one element.
from the doc, JSONObject, length() method:
Returns the number of name/value mappings in this object.
and in your case you have just one name/value mapped ("server_response":[array items...])
Check in Test.java. I think You are setting the adapter to the listview before adding data to it
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
listView = (ListView)findViewById(R.id.test_listView);
dataAdapter = new DataAdapter(this, R.layout.row_layout);
JSON_String = getIntent().getExtras().getString("JSON_Data");
try {
jsonObject = new JSONObject(JSON_String);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String jobid,problem,resolution;
while(count<jsonObject.length()){
JSONObject JO = jsonArray.getJSONObject(count);
jobid = JO.getString("jobid");
problem = JO.getString("problem");
resolution = JO.getString("resolution");
Data data = new Data(jobid,problem,resolution);
dataAdapter.add(data);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setAdapter(dataAdapter); //change effected
}
My data comes dynamically in an array of textviews and I am entering some data in edit texts beside that.
All the data comes in the listview.
what I need to do is I need to transfer all the data in the text views as well as edittexts to another screen on a button click.
How will I achieve that?
Here is my code:
public class S1 extends ListActivity implements OnClickListener {
private ProgressDialog pDialog;
ListView lv;
Button b;
String arry1[], category_main;
int i,key = 0;
private static String url = "http://ashapurasoftech.com/train/test.json";
private static final String TAG_a = "menu",TAG_Name = "Name",TAG_Cat = "Category";
JSONArray items = null;
ArrayList<HashMap<String, String>> itemList;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.table1);
lv =getListView();
category_main = "";
new Getitems().execute(category_main);
b =(Button) findViewById(R.id.start);
b.setOnClickListener(this);
itemList = new ArrayList<HashMap<String, String>>();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_Name, name);
startActivity(in);
}
});
}
#Override
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.start: try {
onbuttonclick();
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
}
private void onbuttonclick() throws JSONException {
Set<String> arry = new HashSet<String>();
for(int k=0;k<items.length();k++)
{
JSONObject c = items.getJSONObject(k);
String category = c.getString(TAG_Cat);
arry.add(category);
}
arry1 = arry.toArray(new String[arry.size()]);
TableRow[] tr = new TableRow[arry1.length];
TextView[] tx = new TextView[arry1.length];
TableLayout tl = (TableLayout) findViewById(R.id.tablelayout1);
for (i = 0; i < arry1.length; i++) {
final String cat = arry1[i].toString();
tx[i] = new TextView(S1.this);
tx[i].setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tx[i].setText(cat);
tr[i] = new TableRow(S1.this);
tr[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tr[i].addView(tx[i],new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tl.addView(tr[i],new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tx[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
category_main = cat;
if (key==0)
{
key=1;
lv.setVisibility(View.VISIBLE);
}
else if(key==1)
{
key=0;
lv.setVisibility(View.GONE);
}
new Getitems().execute(category_main);
}
});
}
b.setVisibility(View.GONE);
}
private class Getitems extends AsyncTask<Void, Void, Void> {
String cat12 = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(S1.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
}
public void execute(String categorymain) {
cat12 = categorymain;
execute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
items = jsonObj.getJSONArray(TAG_a);
for (i = 0; i < items.length(); i++) {
final JSONObject c = items.getJSONObject(i); String cate12 = c.getString(TAG_Cat);
String name = c.getString(TAG_Name);
final HashMap<String, String> item = new HashMap<String, String>();
if(cat12.equalsIgnoreCase(cate12))
{
item.put(TAG_Name,name);
itemList.add(item);
}
}
}
catch (JSONException e) {
e.printStackTrace();
} finally {
}}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
S1.this, itemList,
R.layout.textview, new String[] {TAG_Name},new int[] { R.id.name});
setListAdapter(adapter);
}
}
}