open the object in JSON package - java

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

Related

How to add JSON data to RecyclerView

This is my RecyclerAdapter code:
package com.example.sander.app;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Sander on 6-4-2017.
*/
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.MyViewHolder> {
private String[] mDataset;
ArrayList<String> ArrayDataset;
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView mTextView;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_blah);
}
}
public RecycleAdapter(ArrayList<String> names){
ArrayDataset = names;
}
#Override
public RecycleAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_card_view, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
holder.mTextView.setText(ArrayDataset.get(position));
}
#Override
public int getItemCount() { return ArrayDataset.size(); }
}
And this is my Recycler Fragment code:
package com.example.sander.app;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
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.ArrayList;
import java.util.List;
/**
* Created by Sander on 6-4-2017.
*/
public class RecycleFrame extends Fragment {
ArrayList<String> names = new ArrayList<>();
GoogleMaps maps = new GoogleMaps();
public RecycleFrame() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url= "http://test.dontstealmywag.ga/api/parkgarage.php";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
try{
JSONObject o = new JSONObject(response);
JSONArray values=o.getJSONArray("parkgarage");
for ( int i=0; i< values.length(); i++) {
JSONObject jsonObject = values.getJSONObject(i);
names.add(jsonObject.getString("parkgarage_name"));
}
} catch (JSONException ex){}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
rq.add(stringRequest);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_recycle, container, false);
RecyclerView VRecyclerView = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
VRecyclerView.setHasFixedSize(true);
RecycleAdapter adapter = new RecycleAdapter(names);
VRecyclerView.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
VRecyclerView.setLayoutManager(llm);
return rootView;
}
}
Now if I'm correct. My data from my API (link can be found in the code), will be added in an ArrayList called "names", but when I run my code my Recyclerview is empty. How do I add my JSON data to the RecyclerView and display it.
(For the record if I try it with String [] {"Example"} it will show a card with "Example")
Thanks in advance

How get spinner item position from Fragment to some Class?

I have some dummy problem, I need to get Spinner Item Position from the Fragment to this class:
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Spinner;
import com.example.nortti.politrange.R;
import com.example.nortti.politrange.intefaces.ICatalog;
import com.example.nortti.politrange.objects.Person;
import com.example.nortti.politrange.objects.Site;
import com.example.nortti.politrange.utils.WebApiAdapter;
import com.example.nortti.politrange.views.GeneralFragment;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
public class PersonCatalog implements ICatalog{
private final String COMMAND_PREFIX = "/api/stats/1";
private final WebApiAdapter apiAdapter = new WebApiAdapter(COMMAND_PREFIX);
private ArrayList<Person> catalogList = new ArrayList<Person>();
private Site site;
public PersonCatalog(Site site) {
this.site = site;
}
#Override
public ArrayList<Person> getCatalogList() {
return catalogList;
}
public void populateData() {
JSONArray jsonObject = null;
try {
jsonObject = (JSONArray)(new JSONParser()).parse(apiAdapter.select(null));
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
catalogList.clear();
Iterator<JSONObject> iterator = jsonObject.iterator();
while(iterator.hasNext()) {
JSONObject o = iterator.next();
catalogList.add(new Person((String)o.get("personName"),(int)(long)o.get("rank")));
}
}
}
I broke my head, I don't know how to do it. Please help! Should I use some Intents or create some getters?
UPD: Fragment Code
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import com.example.nortti.politrange.R;
import com.example.nortti.politrange.adapters.GenAdapter;
import com.example.nortti.politrange.adapters.SiteAdapter;
import com.example.nortti.politrange.intefaces.ICatalog;
import com.example.nortti.politrange.intefaces.impls.PersonCatalog;
import com.example.nortti.politrange.intefaces.impls.SitesCatalog;
import com.example.nortti.politrange.objects.Site;
public class GeneralFragment extends Fragment implements OnClickListener, OnItemSelectedListener {
private Button genApply;
private Spinner spinner;
private ListView genList;
private View header;
private ICatalog siteCatalogImpl;
private ICatalog personCatalogImpl;
public int Num;
public void setSpinnerSource(ICatalog siteCatalogImpl) {
this.siteCatalogImpl = siteCatalogImpl;
spinData();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.general_fragment, container,false);
header = inflater.inflate(R.layout.gen_head, null);
spinner = (Spinner) v.findViewById(R.id.wSpin);
spinner.setOnItemSelectedListener(this);
genApply = (Button) v.findViewById(R.id.genApply);
genApply.setOnClickListener(this);
genList = (ListView) v.findViewById(R.id.genList);
genList.addHeaderView(header);
this.setSpinnerSource(new SitesCatalog());
Intent i = new Intent();
i.putExtra("spin", spinner.getSelectedItemPosition()+1);
return v;
}
private void spinData() {
siteCatalogImpl.populateData();
spinner.setAdapter(new SiteAdapter(getActivity(), siteCatalogImpl.getCatalogList()));
}
private void listData(Site site) {
personCatalogImpl = new PersonCatalog(site);
personCatalogImpl.populateData();
genList.setAdapter(new GenAdapter(getActivity(), personCatalogImpl.getCatalogList()));
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onClick(View v) {
int siteIndex = spinner.getSelectedItemPosition();
switch (v.getId()) {
case R.id.genApply:
listData((Site)siteCatalogImpl.getCatalogList().get(siteIndex));
break;
}
}
}
I calling PersonCatalog at the listdata method.
Try this.
final ArrayList<String> providerlist= new ArrayList<String>();
Spinner spinner1 = (Spinner) findViewById(R.id.prospin);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, providerlist);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = providerlist.get(position);
// Showing selected spinner item
Toast.makeText(this,
"Selected Country : " + item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

List view project android

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/

Creating a search app but listview is blank

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

Error while accessing the array

Noob android developer trying to create a gallery with thumbnails saved on my server:
I am trying to use my ArrayList in my ImageAdapter so that I can reference my array values when creating my thumbnail list loop. My eclipse package is available for download here since I may not explain this correctly. When I do trying and reference my "thumb" values in my array I am getting an undefined error along with a syntax error when trying to create my "mThumbIds"
I am not sure why I am having such a hard time understanding this.
showThumb.java:
package com.flash_tattoo;
import android.os.Bundle;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class showThumb extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridlayout);
Bundle bundle = getIntent().getExtras();
String jsonData = bundle.getString("jsonData");
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(jsonData);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<image_data> myJSONArray = new ArrayList<image_data>();
for(int i=0;i<jsonArray.length();i++)
{
JSONObject json_data = null;
try {
json_data = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
try {
image_data.id = json_data.getInt("id");
} catch (JSONException e) {
e.printStackTrace();
}
try {
image_data.name = json_data.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
try {
image_data.thumb = json_data.getString("thumb");
} catch (JSONException e) {
e.printStackTrace();
}
try {
image_data.path = json_data.getString("path");
} catch (JSONException e) {
e.printStackTrace();
}
myJSONArray.add(new image_data());
}
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this,myJSONArray));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(showThumb.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
}
ImageAdapter:
package com.flash_tattoo;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
public class ImageAdapter extends ArrayAdapter<image_data>
{
//This code below was put in when I change from BaseAdapter to ArrayAdapter
public ImageAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
private Context mContext;
public int getCount() {
return mThumbIds.length;
}
public image_data getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
for(int i=0;i<myJSONArray.lenght();i++){
Object[] myJSONArray;
setImageDrawable(Drawable.createFromPath(myJSONArray[i].thumb)
};
};
}
You have there a private field mThumbIds of type Integer[] and you're trying to initialize it inline, but you fail to do so because you have an static block {} with statements.
I would say you need to just declare:
private Integer[] mThumbIds;
then, in the constructor you can populate the array.

Categories