Intent with ListView (JSON data) - android

I put JSON data to the ListView. I want data in the list("ItemTitle", "ItemText", "latit", "longit", "date") can transfer to another activity(result.java)when item is clicked. Here are the code:
activity:
public class Earthquake extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.earthquake);
getData();
}
private void getData() {
// TODO Auto-generated method stub
ListView list = (ListView)findViewById(R.id.earthquake);
try {
List<News> newes = GetJson.update();
List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
for(News news : newes){
HashMap<String, Object> item = new HashMap<String, Object>();
item.put("ItemTitle", news.getPlace());
item.put("ItemText", "Magnitude: "+news.getMag());
item.put("latit", news.getLatit());
item.put("longit", news.getLongit());
item.put("date", news.getTime());
data.add(item);
}
SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.list_earthquake,
new String[]{"ItemTitle", "ItemText", "latit", "longit", "date"},
new int[]{R.id.ItemTitle, R.id.ItemText, R.id.latit, R.id.longit, R.id.date});
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
//intent
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
GetJson.java:
public class GetJson {
public static List<News> update() throws Exception, IOException {
// TODO Auto-generated method stub
String path = "http://earthquake.usgs.gov/earthquakes/feed/geojson/all/hour";
HttpURLConnection conn = (HttpURLConnection)new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == 200){
InputStream json = conn.getInputStream();
return parseJSON(json);
}
return null;
}
private static List<News> parseJSON(InputStream jsonStream) throws Exception {
// TODO Auto-generated method stub
List<News> list = new ArrayList<News>();
byte[] data = StreamTool.read(jsonStream);
String json = new String(data);
//start decoad JSON
JSONObject jsonObject1 = new JSONObject(json);
String object1 = jsonObject1.getString("features");
JSONArray features = new JSONArray(object1);
for(int i = 0; i < features.length(); i++){
JSONObject object2 = features.getJSONObject(i);
JSONObject properties = object2.getJSONObject("properties");
String place = properties.getString("place");
int mag = properties.getInt("mag");
String time = properties.getString("time");
JSONObject geometry = object2.getJSONObject("geometry");
JSONArray coordinates = geometry.getJSONArray("coordinates");
String longit = coordinates.getString(0);
String latit = coordinates.getString(1);
list.add(new News(mag, longit, latit, place, time));
}
return list;
}
}
News.java:
public class News {
private Integer mag;
private String longit;
private String latit;
private String place, time;
public News(){}
public News(Integer mag, String longit, String latit, String place, String time){
this.mag = mag;
this.longit = longit;
this.latit = latit;
this.place = place;
this.time = time;
}
public Integer getMag(){
return mag;
}
public String getLongit(){
return longit;
}
public String getLatit(){
return latit;
}
public String getPlace(){
return place;
}
public String getTime(){
return time;
}
}
Thanks!!

I suggest you rewrite your SimpleAdapter to extends ArrayAdapter<News>. Creating another List of HasMaps is quite useless and consumes additional memory. Than make your News class implement Parcelable. And in onClick() you call something like:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
News news = parent.getItem(position);
if (news != null) {
Intent intent = new Intent(...);
intent.put("news", news);
startActivity(intent);
}
}

Always use a non-UI thread to fetch data from servers. Looking at your code it looks like you are using the UI thread to fetch data. You may use AsyncTask and paste the code written in the GetJson class in the doInBackground method of an AsyncTask object.
Now about your problem to pass the clicked list item data to the next activity. You will have to either make the class News implement Parcelable or Serializable interface. implementing these classes allows you to send the custom object data to another activity. The most efficient way is to implement Parcelable.
Check the following links for more details:
http://developer.android.com/reference/android/os/Parcelable.html
http://developer.android.com/reference/java/io/Serializable.html
Hope this explanation helps.

Related

three categories item list get with diffrent category_id from json data in recyclerview android

I am developing an android app in which i store data from json.
everything is working fine but i am trying to implement multilayout Recyclerview where i show first and second category list items in a box with horizontal scroll and third list which we get from Category_id from json in vertical list
i get data from server in json where category list is open with unique category id just like
http://example.com/file_path&Category_id=3
and i get json data like
json data for category
[
{
"Category_ID":"3",
"Category_name":"Camera",
"Category_image":"upload\/images\/7089-2015-07-09.png"
},
{
"Category_ID":"9",
"Category_name":"Cars",
"Category_image":"upload\/images\/7789-2015-07-09.png"
},
]
json data for category list item
category list item json data. Every category list have unique id.
[
{
"Menu_ID":"19",
"Menu_name":"Sample 6",
"Price":"380",
"Menu_image":"upload\/images\/8611-2015-02-11.jpg"
},
{
"Menu_ID":"18",
"Menu_name":"Sample 5",
"Price":"500",
"Menu_image":"upload\/images\/8119-2015-02-11.jpg"
}
]
i am using recyclerview to show category and by clicking on category item category list is open
but i dont know how to call diffrent category list item from diffrent json category_id in a same recyclerview just like this image
Code is something like
MainActivity.java
public class ActivityProductList extends AppCompatActivity {
List<DataProductAdapter> ListOfdataAdapter;
RecyclerView recyclerView;
String HTTP_JSON_URL = "http: //example.com";
String Menu_Price_JSON = "Price";
String Menu_ID_JSON = "Menu_ID";
String Menu_Name_JSON = "Menu_name";
String Menu_Image_JSON = "Menu_image";
JsonArrayRequest RequestOfJSonArray ;
RequestQueue requestQueue ;
View view ;
int RecyclerViewItemPosition ;
RecyclerView.LayoutManager layoutManagerOfrecyclerView;
RecyclerView.Adapter recyclerViewadapter;
ArrayList<String> ImageTitleNameArrayListForClick;
public static ArrayList<Long> Menu_ID = new ArrayList<Long>();
public static ArrayList<String> Menu_name = new ArrayList<String>();
public static ArrayList<Double> Menu_price = new ArrayList<Double>();
public static ArrayList<String> Menu_image = new ArrayList<String>();
ProgressBar prgLoading;
SwipeRefreshLayout swipeRefreshLayout = null;
EditText edtKeyword;
ImageButton btnSearch;
TextView txtAlert;
public static double Tax;
public static String Currency;
String MenuAPI;
String TaxCurrencyAPI;
int IOConnect = 0;
long Category_ID;
String Category_name;
String Keyword;
// create price format
DecimalFormat formatData = new DecimalFormat("#.##");
private RecViewProductAdapter mla;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product);
ImageTitleNameArrayListForClick = new ArrayList<>();
mla = new RecViewProductAdapter(ActivityProductList.this);
// menu API url
MenuAPI = examplelink+"&category_id=";
// tax and currency API url
TaxCurrencyAPI = examplelink2;
Intent iGet = getIntent();
Category_ID = iGet.getLongExtra("category_id",0);
Category_name = iGet.getStringExtra("category_name");
MenuAPI += Category_ID;
ListOfdataAdapter = new ArrayList<>();
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
edtKeyword = (EditText) findViewById(R.id.edtKeyword);
btnSearch = (ImageButton) findViewById(R.id.btnSearch);
txtAlert = (TextView) findViewById(R.id.txtAlert);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview_prod);
recyclerView.setHasFixedSize(true);
layoutManagerOfrecyclerView = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManagerOfrecyclerView);
recyclerViewadapter = new RecViewProductAdapter(ListOfdataAdapter, getApplicationContext());
recyclerView.setAdapter(recyclerViewadapter);
// JSON_HTTP_CALL();
new getTaxCurrency().execute();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
IOConnect = 0;
clearData();
new getDataTask().execute();
}
}, 3000);
}
});
// Implementing Click Listener on RecyclerView.
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View arg1, int position)
{
// TODO: Implement this method
AdapterView<?> arg0;
long arg3;
Intent iDetail = new Intent(ActivityProductList.this, ActivityMenuDetail.class);
iDetail.putExtra("menu_id", Menu_ID.get(position));
startActivity(iDetail);
}
})
);
}
public class getTaxCurrency extends AsyncTask<Void, Void, Void>{
// show progressbar first
getTaxCurrency(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(View.VISIBLE);
txtAlert.setVisibility(View.GONE);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONDataTax();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(View.GONE);
// if internet connection and data available request menu data from server
// otherwise, show alert text
if((Currency != null) && IOConnect == 0){
new getDataTask().execute();
}else{
txtAlert.setVisibility(View.VISIBLE);
}
}
}
public void parseJSONDataTax(){
try {
// request data from tax and currency API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(TaxCurrencyAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into tax and currency variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
JSONObject object_tax = data.getJSONObject(0);
JSONObject tax = object_tax.getJSONObject("tax_n_currency");
Tax = Double.parseDouble(tax.getString("Value"));
JSONObject object_currency = data.getJSONObject(1);
JSONObject currency = object_currency.getJSONObject("tax_n_currency");
Currency = currency.getString("Value");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
IOConnect = 1;
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// clear arraylist variables before used
// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{
// show progressbar first
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(View.VISIBLE);
txtAlert.setVisibility(View.GONE);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(View.GONE);
// if data available show data on list
// otherwise, show alert text
if(Menu_ID.size() > 0){
recyclerView.setVisibility(View.VISIBLE);
recyclerView.setAdapter(mla);
}else{
txtAlert.setVisibility(View.VISIBLE);
}
}
}
void clearData(){
Menu_ID.clear();
Menu_name.clear();
Menu_price.clear();
Menu_image.clear();
}
// method to parse json data from server
public void parseJSONData(){
clearData();
try {
// request data from menu API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(MenuAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into arraylist variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject menu = object.getJSONObject("Menu");
Menu_ID.add(Long.parseLong(menu.getString("Menu_ID")));
Menu_name.add(menu.getString("Menu_name"));
Menu_price.add(Double.valueOf(formatData.format(menu.getDouble("Price"))));
Menu_image.add(menu.getString("Menu_image"));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
//mla.imageLoader.clearCache();
recyclerView.setAdapter(null);
super.onDestroy();
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
}
adapter class
public class RecViewProductAdapter extends RecyclerView.Adapter<RecViewProductAdapter.ViewHolder> {
Context context;
List<DataProductAdapter> dataAdapters;
ImageLoader imageLoader;
private ActivityProductList _mainActivity;
private Activity activity;
public RecViewProductAdapter(ActivityProductList activity){
this._mainActivity=activity;
}
public RecViewProductAdapter(Activity act) {
this.activity = act;
}
public RecViewProductAdapter(List<DataProductAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.lsv_item_menu_list, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
View convertView = null;
holder.menuname.setText(ActivityProductList.Menu_name.get(position));
holder.menuprice.setText(ActivityProductList.Menu_price.get(position)+" "+ActivityProductList.Currency);
Picasso.with(activity).load(Config.ADMIN_PANEL_URL+"/"+ActivityProductList.Menu_image.get(position)).placeholder(R.drawable.loading).into(holder.imgThumb);
}
#Override
public int getItemCount() {
return ActivityProductList.Menu_ID.size();
// return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView txtText, txtSubText;
ImageView imgThumb;
public TextView menuname, menuprice, menunid;
public NetworkImageView VollyImageView ;
public ViewHolder(View itemView) {
super(itemView);
menuname = (TextView) itemView.findViewById(R.id.txtText);
menuprice = (TextView) itemView.findViewById(R.id.txtSubText);
imgThumb = (ImageView) itemView.findViewById(R.id.imgThumb);
}
}
}
any idea how can i achieve that layout with above code?
thankx

Android: ListView from MySQL only display the last element

I'm trying to retrieve data from MySql database and put it on a ListView, everything works fine, I even put that data into textviews(dynamically) and it works fine. But when I used a ListView, only the last element was displayed, I think that means every new element is overwritten the old one, right?
What can I do to solve this? here's my code tell what's wrong??
public class MakeAppointementActivity extends AppCompatActivity {
public List<AvailabilityList> customList;
public ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_appointement);
lv=(ListView)findViewById(R.id.listView);
Intent intent=getIntent();
new RetrieveTask().execute();
}
private class RetrieveTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String strUrl = "availableAppointments1.php";
URL url;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line;
while( (line = reader.readLine()) != null){
sb.append(line);
}
reader.close();
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(result);
}
}
// Background thread to parse the JSON data retrieved from MySQL server
private class ParserTask extends AsyncTask<String, Void, List<HashMap<String, String>>> {
#Override
protected List<HashMap<String, String>> doInBackground(String... params) {
AppointementJSONParser appointementParser = new AppointementJSONParser();
JSONObject json = null;
try {
json = new JSONObject(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
return appointementParser.parse(json);
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
customList=new ArrayList<>(); / move it to here
for (int i = 0; i < result.size(); i++) {
HashMap<String, String> appointement = result.get(i);
String fromT = appointement.get("fromT");
String toT = appointement.get("toT");
String date = appointement.get("date");
addAvailableAppoint(fromT,toT,date);
}
updateListView(); // update listview when you add all data to arraylist
}
}
private void addAvailableAppoint(final String fromT, final String toT, final String date) {
customList.add(new AvailabilityList(fromT));
}
// split new function for update listview
private updateListView(){
ArrayAdapter adapter=new DoctorAvailabilityAdapter(MakeAppointementActivity.this,R.layout.list_items,customList);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MakeAppointementActivity.this, AppointementActivity.class);
intent.putExtra("fromT", fromT);
intent.putExtra("toT", toT);
intent.putExtra("date", date);
startActivity(intent);
}
});
}
}
Try this code
.....// your above code
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
customList=new ArrayList<>(); / move it to here
for (int i = 0; i < result.size(); i++) {
HashMap<String, String> appointement = result.get(i);
String fromT = appointement.get("fromT");
String toT = appointement.get("toT");
String date = appointement.get("date");
addAvailableAppoint(fromT,toT,date);
}
updateListView(); // update listview when you add all data to arraylist
}
}
private void addAvailableAppoint(final String fromT, final String toT, final String date) {
customList.add(new AvailabilityList(fromT));
}
// split new function for update listview
private updateListView(){
ArrayAdapter adapter=new DoctorAvailabilityAdapter(MakeAppointementActivity.this,R.layout.list_items,customList);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MakeAppointementActivity.this, AppointementActivity.class);
// intent.putExtra("fromT", fromT); // change it to
intent.putExtra("fromT", customList.get(position).getFromT());
intent.putExtra("toT", toT);
intent.putExtra("date", date);
startActivity(intent);
}
});
}
}
Hope this help
You create new ArrayList for every item customList=new ArrayList<>();
Create list only once in OnCreate for example.
Also you create new Adapter every time you add an item, adapter should also be created only once in OnCreate then you should update data with adapter.NotifyDataSetChanged()

How to add some parsed JSON objects into a custom listview?

Well, I don't know if the title is clear, so now I'll explain everything better.
I have parsed some JSON objects. After parsing, I need to show them into a custom listview.
The JSON objects are correctly parsed into string, because I have first show them into common textviews (just for a test).
Also the custom listview is working, because I have first added some values "manually" (again, just for testing it).
Here my problem:
Now I want to add the JSON objects (parsed into string) into my custom listview. I've tried every "tip and trick" I know, unsuccessfully. After two days of working, I've decided to ask you.
Before posting the code: the http request for parsing JSON objects is made with this library.
Here the code
Getprofiledata.java
public class Getprofiledata extends ActionBarActivity {
String num;
Boolean ok=true;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data);
String url = "URL FOR JSON OBJECTS";
ListView listadata = (ListView) findViewById(R.id.listadata);
final List<Data> datalist = new LinkedList <Data>();
AsyncHttpClient client = new AsyncHttpClient();
client.get(url,new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
ok=true;
i=1;
num = Integer.toString(i);
while(ok==true){
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject object = jsonObject.getJSONObject(num);
/*********
* THESE ARE THE STRINGS I NEED TO ADD TO MY CUSTOM LISTVIEW
*********/
String record1 = object.getString("first");
String record2 = object.getString("second");
String record3 = object.getString("third");
String record4 = object.getString("fourth");
String record5 = object.getString("fiveth");
i++;
num = Integer.toString(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ok=false;
}
}
}
#Override
public void onFailure(Throwable e,String response) {
Log.d("AREQ","http GET request failed");
}
});
/*********
* HERE WE CAN ADD VALUES TO MY CUSTOM LISTVIEW
* HOW CAN I PASS THE PREVIOUS STRING IN THIS STATEMENT?
*
* THIS IS THE METHOD:
* datalist.add(new Data(record1,record2,record3,record4,record5));
*********/
//HERE THE ADAPTER FOR MY CUSTOM LISTVIEW
Getprofiledata_customadapter adapter = new Getprofiledata_customadapter(this, R.layout.data_riga, datalist);
listadata.setAdapter(adapter);
}
}
I hope I've been clear. Can you help me? I'm desperate! :(
Thanks in advance
Edit: here my Getprofiledata_customadapter.java
public class Getprofiledata_customadapter extends ArrayAdapter<Data>{
public Getprofiledata_customadapter(Context context, int textViewResourceId,
List <Data> objects) {
super(context, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.data_riga, null);
TextView firstrecord = (TextView)convertView.findViewById(R.id.tv1);
TextView secondrecord = (TextView)convertView.findViewById(R.id.tv2);
TextView thirdrecord = (TextView)convertView.findViewById(R.id.tv3);
TextView forthrecord = (TextView)convertView.findViewById(R.id.tv4);
TextView fivethrecord = (TextView)convertView.findViewById(R.id.tv5);
Data c = getItem(position);
firstrecord.setText(c.getRecord1());
secondrecord.setText(c.getRecord2());
thirdrecord.setText(c.getRecord3());
forthrecord.setText(c.getRecord4());
fivethrecord.setText(c.getRecord5());
return convertView;
}
}
Basically you just pre-create the List first. Then with that data create an adapter and set it to your ListView.
At the moment you just loop through the data without saving it at all.
It would look something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data);
mListView = (ListView) findViewById(R.id.listadata);
String url = "URL FOR JSON OBJECTS";
AsyncHttpClient client = new AsyncHttpClient();
client.get(url,new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
ok=true;
i=1;
num = Integer.toString(i);
while(ok==true){
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject object = jsonObject.getJSONObject(num);
/*********
* THESE ARE THE STRINGS I NEED TO ADD TO MY CUSTOM LISTVIEW
*********/
String record1 = object.getString("first");
String record2 = object.getString("second");
String record3 = object.getString("third");
String record4 = object.getString("fourth");
String record5 = object.getString("fiveth");
// Save strings to your list
mData.add(new Data(record1,record2,record3,record4,record5));
i++;
num = Integer.toString(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ok=false;
}
}
// When the data loop is over create the adapter and set it to your ListView
Getprofiledata_customadapter adapter = new Getprofiledata_customadapter(this,
R.layout.data_riga, mData);
mListView.setAdapter(adapter);
}
#Override
public void onFailure(Throwable e,String response) {
Log.d("AREQ","http GET request failed");
}
});
}

Listview is getting the value twice

I have a API which responds in JSON. When I clicked a button I am comfortably parse the JSON and implement it in the listview. The problem is When I go back to the previous activity and clicked the button once again I am getting the values repeat. i.e. previous values also, even I had called finish(); in on pause state of the listview activity. Following is my code.
Invoice Class
public class Invoice extends Activity{
public static ArrayList<HashMap<String, String>> ModuleName = new ArrayList<HashMap<String, String>>();
boolean tree = true;
ArrayList<String> KEY = new ArrayList<String>();
ListView mListView;
ProgressBar mProgress;
JSONObject json;
JSONArray Module_list = null;
Invoice_adapter adapter;
public static String KEY_SUCCESS = "success";
public static String KEY_ERROR = "error";
public static String KEY_ERROR_MSG = "error_msg";
public static String KEY_MODULELIST_MODULEHEADER = "moduleHeader";
public static String KEY_MODULELIST_MODULELIST = "moduleList";
public static String KEY_MODULELIST_DATAFOUND = "datafound";
public static String KEY_INVOICE_INVOICENO = "";
public static String KEY_INVOICE_SUBJECT = "";
public static String KEY_INVOICE_SALESORDER = "";
public static String KEY_INVOICE_STATUS = "";
public static String KEY_INVOICE_TOTAL = "";
public static String KEY_INVOICE_ASSIGNEDTO = "";
public static String KEY_INVOICE_RECORDID = "";
public static String KEY_INVOICE_ACTION = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_module_data);
mListView = (ListView) findViewById(R.id.module_list);
mProgress = (ProgressBar) findViewById(R.id.progressBar1);
try {
json = new ParseDATA().execute().get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
String data_found = json.getString(KEY_MODULELIST_DATAFOUND);
if (data_found.equals("Data Found!")){
JSONArray array = json.getJSONArray(KEY_MODULELIST_MODULELIST);
int count1 = array.length();
String Count1 = Integer.toString(count1);
Log.d("Count_array", Count1);
JSONObject keyarray = array.getJSONObject(0);
#SuppressWarnings("rawtypes")
Iterator temp = keyarray.keys();
while (temp.hasNext()) {
String curentkey = (String) temp.next();
KEY.add(curentkey);
}
Collections.sort(KEY, String.CASE_INSENSITIVE_ORDER);
KEY_INVOICE_ACTION = KEY.get(0);
KEY_INVOICE_ASSIGNEDTO = KEY.get(1);
KEY_INVOICE_INVOICENO = KEY.get(2);
KEY_INVOICE_RECORDID = KEY.get(3);
KEY_INVOICE_SALESORDER = KEY.get(4);
KEY_INVOICE_STATUS = KEY.get(5);
KEY_INVOICE_SUBJECT = KEY.get(6);
KEY_INVOICE_TOTAL = KEY.get(7);
Log.d("Parsing Json class", " ---- KEYS---- " + KEY);
Module_list = json.getJSONArray(KEY_MODULELIST_MODULELIST);
int count = Module_list.length();
String Count = Integer.toString(count);
Log.d("Count_Module_LIST", Count);
// looping through All Contacts
for(int i = 0; i < Module_list.length(); i++){
JSONObject c = Module_list.getJSONObject(i);
// Storing each json item in variable
String mAction = c.getString(KEY_INVOICE_ACTION);
String mAssignedTo = c.getString(KEY_INVOICE_ASSIGNEDTO);
String mInvoice = c.getString(KEY_INVOICE_INVOICENO);
String mRecordid = c.getString(KEY_INVOICE_RECORDID);
String mSalesorder = c.getString(KEY_INVOICE_SALESORDER);
String mStatus = c.getString(KEY_INVOICE_STATUS);
String mSubject = c.getString(KEY_INVOICE_SUBJECT);
String mTotal = c.getString(KEY_INVOICE_TOTAL);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_INVOICE_ACTION, mAction);
map.put(KEY_INVOICE_ASSIGNEDTO, mAssignedTo);
map.put(KEY_INVOICE_INVOICENO, mInvoice);
map.put(KEY_INVOICE_RECORDID, mRecordid);
map.put(KEY_INVOICE_SALESORDER, mSalesorder);
map.put(KEY_INVOICE_STATUS, mStatus);
map.put(KEY_INVOICE_SUBJECT, mSubject);
map.put(KEY_INVOICE_TOTAL, mTotal);
// adding HashList to ArrayList
ModuleName.add(map);
}
}else
{
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
return;
}
}
mProgress.setVisibility(View.INVISIBLE);
adapter = new Invoice_adapter(Invoice.this, ModuleName);
mListView.setAdapter(adapter);
mListView.setVisibility(View.VISIBLE);
//mListView.invalidateViews();
}
else
{
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ERROR, "Error");
ModuleName.add(map);
//JSONObject json_user = json.getJSONObject("user");
//error_message = json_user.getString(KEY_ERROR_MSG);
}
}catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Something went wrong.Please try again.!!", Toast.LENGTH_LONG).show();
}
}
class ParseDATA extends AsyncTask<Void, String,JSONObject >
{
ProgressDialog dialog = new ProgressDialog(Invoice.this);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setTitle("Loading");
dialog.setIndeterminate(true);
dialog.setMessage("Please wait");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected JSONObject doInBackground(
Void... params) {
// TODO Auto-generated method stub
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.getModuleList("1", "20", "Invoice");
return json;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
dialog.dismiss();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(getApplicationContext(), "PAUSE STATE", Toast.LENGTH_LONG).show();
finish();
}}
Adapter class
public class Invoice_adapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public Invoice_adapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.activity_module_data_detail, null);
TextView title = (TextView)vi.findViewById(R.id.textView1); // category title name
//ImageView moduleImage = (ImageView) vi.findViewById(R.id.recipe_image);
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
Log.i("list", ""+data.get(position));
//Log.i("list", data);
String ff = song.get(Invoice.KEY_INVOICE_SUBJECT);
title.setText(ff);
//moduleImage.setImageResource(mModuleImages[position]);
return vi;
}}
Please Help.. !! I dnt know what Is I am doing wrong.
Thanks in advance.
The problem is with the "static" key word for the ArrayList
public static ArrayList<HashMap<String, String>> ModuleName = new ArrayList<HashMap<String, String>>();
static variables are initialized only when the class is loaded, that means the value will be persisted till the end of the application process.
Either remove static keyword for array list or clear the array list before you load new data.
ModuleName.clear();

populating multiple data into android listview

I am trying to learn populating data from the server to Listview.
I am new to android
MainActivity.java
public class MainActivity extends Activity {
// url to make request
private static String url = "http://URL:7002/";
private static String url1 = "http://URL:7002/XXX";
//private HashMap<Integer, String> TimeMap = new HashMap<Integer, String>();
List<Item> yourData = new ArrayList<Item>();
List<Item> yourData1 = new ArrayList<Item>();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Instantiating ProgressDialog with onCreate method
progressDialog=new ProgressDialog(MainActivity.this);
new ParsingAsync().execute();
}
private class ParsingAsync extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog=ProgressDialog.show(MainActivity.this, "", "Please Wait", true, false);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Creating JSON Parser instance
JSONObjParser jParser = new JSONObjParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
// getting JSON string from URL
JSONArray json1 = jParser.getJSONFromUrl(url1);
try {
for (int i = 0; i < json1.length(); i++) {
JSONObject c = json1.getJSONObject(i);
// Storing each json item in variable
int id = c.getInt("_id");
String TIME = c.getString("RestaurantTime");
yourData1.add(new Item(TIME));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
for (int i = 0; i < json.length(); i++) {
JSONObject c = json.getJSONObject(i);
// Storing each json item in variable
String NAME=c.getString("restaurantNAME");
yourData.add(new Item(NAME));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressDialog.dismiss();
//TextView timedisplay=(TextView) findViewById(R.id.RestaurantTimeID);
ListView yourListView = (ListView) findViewById(R.id.listViewID);
ListAdapter customAdapter = new ListAdapter(MainActivity.this, R.layout.itemlistrow, yourData);
yourListView.setAdapter(customAdapter);
// remaining code
ListAdapter.java
public class ListAdapter extends ArrayAdapter<Item> {
private List<Item> items;
public ListAdapter(Context context, int resource, List<Item> items) {
super(context, resource, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView tt = null;
TextView time=null;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.itemlistrow, null);
tt = (TextView) v.findViewById(R.id.RestaurantNameID);
time = (TextView) v.findViewById(R.id.RestaurantTimeID);
}
Item p = items.get(position);
if (p != null) {
if (tt != null) {
tt.setText(""+p.getName());
}
if (time != null) {
time.setText(""+p.getTime());
}
}
return v;
}
}
Item.java
public class Item{
private String Name;
private String Time;
public Item(String name){
this.Name = name;
}
public String getName(){
return Name;
}
public void Time(String time){
this.Time = time;
}
public String getTime(){
return Time;
}
}
How can i resolve this
I have posted required classes above
Using List for populating the data is i am looking at
Any ideas,
Thanks.
You set TIME to yourdata1 and NAME to yourdata. The objects of yourdata1 only contains TIME and the NAME is null. The objects of yourdata only contains NAME and the TIME is null.
Please set NAME and TIME in one object and store it in one List which will be passed to ListAdapter.
I hope you can understand me.
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Creating JSON Parser instance
JSONObjParser jParser = new JSONObjParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
// getting JSON string from URL
JSONArray json1 = jParser.getJSONFromUrl(url1);
// assume json's length is the same as json1's
try {
for (int i = 0; i < json1.length(); i++) {
JSONObject c = json1.getJSONObject(i);
Item item = new Item();
// Storing each json item in variable
int id = c.getInt("_id");
String TIME = c.getString("RestaurantTime");
item.setTime(TIME);
c = json.getJSONObject(i);
// Storing each json item in variable
String NAME=c.getString("restaurantNAME");
item.setName(NAME);
yourData.add(item);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
and
public class Item{
private String Name;
private String Time;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
Time = time;
}
}

Categories

Resources