No load data anymore except refresh action - android

I couldn't find a solution to my problem on the search engine, So i decided to ask here.
I have navigation tab with 3 fragments fragmentA, fragmentB, fragmentC. Each fragment load data from parsed data. i have opened fragment a and load data on listview, then i want to change to fragment b, and load the data too. but when i want to go back to fragmentA the fragment loads the data again.
I want my fragment are saving the loaded data before and when i refresh the fragment, the fragment load new data. An example app like a twitter or facebook. What i have to do? thanks for reading
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View Vi = inflater.inflate(R.layout.list_kuliah, container, false);
//Hashmap for ListView
contactList = new ArrayList<HashMap<String, String>>();
progress = (LinearLayout) Vi.findViewById(R.id.linlaHeaderProgress);
ListView lv = (ListView) Vi.findViewById(R.id.list1);
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.title))
.getText().toString();
String email = ((TextView) view.findViewById(R.id.publisher))
.getText().toString();
String address = ((TextView) view.findViewById(R.id.description))
.getText().toString();
//String thumb_url = ((ImageView))
// Starting single contact activity
Intent in = new Intent(getActivity() ,SingleKuliahAct.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, email);
in.putExtra(TAG_ADDRESS, address);
startActivity(in);
getActivity().overridePendingTransition( R.anim.left1, R.anim.left2 );
}
});
new MyAsyncTask().execute();
return Vi;
}
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progress.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... args0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
//getting JSON string from URL
String jsonStr = sh.makeServiceCall(url_contacts, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
contact.put(TAG_ADDRESS, address);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
/**
* Updating parsed JSON data into ListView
* */
/*ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_kuliah_item, new String[] { TAG_NAME, TAG_EMAIL, TAG_ADDRESS}, new int[] { R.id.title,
R.id.publisher, R.id.description });
ListView mView = (ListView)
getView().findViewById(R.id.list1);
mView.setAdapter(adapter);*/
KuliahAdapter adapter;
ListView List = (ListView) getView().findViewById(R.id.list1);
adapter = new KuliahAdapter(getActivity(), contactList);
List.setAdapter(adapter);
progress.setVisibility(View.GONE);
}
above is my code on fragment kuliah (fragment A), and i have adapter for each fragment
public class KuliahAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public KuliahAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return 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.list_kuliah_item, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.publisher); // artist name
TextView duration = (TextView)vi.findViewById(R.id.description); // duration
//TextView countcomment = (TextView)vi.findViewById(R.id.countcomment); // duration
//TextView countlikes = (TextView)vi.findViewById(R.id.countlikes); // duration
//TextView created = (TextView)vi.findViewById(R.id.created); // created
//ImageView thumb_image=(ImageView)vi.findViewById(R.id.image); // default image
HashMap<String, String> contactList = new HashMap<String, String>();
contactList = data.get(position);
// Setting all values in listview
title.setText(contactList.get(KuliahFragment.TAG_NAME));
artist.setText(contactList.get(KuliahFragment.TAG_EMAIL));
duration.setText(contactList.get(KuliahFragment.TAG_ADDRESS));
//countcomment.setText(courses.get(KuliahFragment.TAG_COUNTCOMMENT));
//countlikes.setText(courses.get(KuliahFragment.TAG_COUNTLIKES));
//created.setText(courses.get(KuliahFragment.TAG_CREATED));
//imageLoader.DisplayImage(courses.get(KuliahFragment.TAG_IMAGE), thumb_image);
return vi;
}
}

Related

how to match string value in" if else" condition in android?

here i am displaying 1 listview which is coming from server.if i click on any item i want some alertbox to open...but for that i need match the condition eg.if listitem string matches with "Bianca pizza" then open alertbox else toast "hello"..here in my code its not taking listview item string .
its weird its taking 1st value of listview item in toast (the code which i put before if condition just to check whether its correct or not.)but when i am comparing its not working.
like in toast i m getting "Bianca pizza" but when i want to compare it with "Bianca Pizza" it should match and go inside the if condition but its not going inside and showing else condition.
here is my code:
public class SubMenu extends AppCompatActivity {
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "id";
static String COUNTRY = "name";
private ProgressDialog pDialog;
String status="";
static String FLAG = "image";
Integer i = 1;
String _stringVal;
private static String url_create_book = "http://cloud....com/broccoli/creatinfo.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_menu);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
String SelectedId = getIntent().getStringExtra("id");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Get the view from listview_main.xml
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> implements AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener {
// #Override
// protected void onPreExecute() {
// super.onPreExecute();
// Create a progressdialog
// mProgressDialog = new ProgressDialog(SubMenu.this);
// Set progressdialog title
// mProgressDialog.setTitle("Categories of Main categories.....");
// Set progressdialog message
// mProgressDialog.setMessage("Loading...");
// mProgressDialog.setIndeterminate(false);
// Show progressdialog
// mProgressDialog.show();
// }
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonarray = JsonFunctions
.getJSONfromURL("http://cloud....com/broccoli/menu_typeitem.php?id=" + getIntent().getStringExtra("id"));
try {
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
map.put("name", jsonobject.getString("name"));
map.put("image", jsonobject.getString("image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.list1);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(SubMenu.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
listview.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long rowId) {
TextView name = (TextView) parent.findViewById(R.id.type1);
Toast.makeText(SubMenu.this, "this is "+name.getText(), Toast.LENGTH_SHORT).show();
if ( name.getText().toString().equalsIgnoreCase("Bian‌​‌​ca Pizza"))
{
//open alertbox
}
else{
Toast.makeText(SubMenu.this, "hello", Toast.LENGTH_SHORT).show();
}
here is my listview adapter:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView id;
TextView name;
TextView population;
CircleImageView image;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.list_item1, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
// id = (TextView) itemView.findViewById(R.id.idq);
name = (TextView) itemView.findViewById(R.id.type1);
// Locate the ImageView in listview_item.xml
image = (CircleImageView) itemView.findViewById(R.id.subimg);
// icon = (ImageView) itemView.findViewById(R.id.arrow);
// Capture position and set results to the TextViews
// id.setText(resultp.get(SubMenu.RANK));
name.setText(resultp.get(SubMenu.COUNTRY));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(SubMenu.FLAG), image);
// imageLoader.DisplayImage(resultp.get(SubMenu.FLAG), icon);
// Capture ListView item click
/**itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("rank", resultp.get(MainActivity.RANK));
// Pass all data country
intent.putExtra("country", resultp.get(MainActivity.COUNTRY));
// Pass all data population
intent.putExtra("population",resultp.get(MainActivity.POPULATION));
// Pass all data flag
intent.putExtra("flag", resultp.get(MainActivity.FLAG));
// Start SingleItemView Class
context.startActivity(intent);
}
});*/
return itemView;
}
}
The problem is that you used parent ! parent is the whole adapter view and it contains lots of rows in which there is a Textview with id `R.id.type1. When you use parent, it find the first item with that id in its hierarchy. That's why it always return first item.
you should do this :
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long rowId) {
// TextView name = (TextView) parent.findViewById(R.id.type1); WRONG
TextView name = (TextView) view.findViewById(R.id.type1);
Toast.makeText(SubMenu.this, "this is "+name.getText(), Toast.LENGTH_SHORT).show();
if ( name.getText().toString().equalsIgnoreCase("Bian‌​‌​ca Pizza"))
{
//open alertbox
}
else {
Toast.makeText(SubMenu.this, "hello", Toast.LENGTH_SHORT).show();
}
}
The only change you would need to do is Use view instead of parent on onItemClick, please refer below - This will get the clicked item text directly.
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long rowId) {
TextView name = (TextView) view.findViewById(R.id.type1);
Toast.makeText(SubMenu.this, "this is "+name.getText(), Toast.LENGTH_SHORT).show();
if ( name.getText().toString().equals("Bian‌​‌​ca Pizza"))
{
//open alertbox
}
else{
Toast.makeText(SubMenu.this, "hello", Toast.LENGTH_SHORT).show();
}
I think this helpful for you.
Firstly you close DownloadJSON class before on item click then call onitem click function.
private class DownloadJSON extends AsyncTask<Void, Void, Void> implements
AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener {
// #Override
// protected void onPreExecute() {
// super.onPreExecute();
// Create a progressdialog
// mProgressDialog = new ProgressDialog(SubMenu.this);
// Set progressdialog title
// mProgressDialog.setTitle("Categories of Main categories.....");
// Set progressdialog message
// mProgressDialog.setMessage("Loading...");
// mProgressDialog.setIndeterminate(false);
// Show progressdialog
// mProgressDialog.show();
// }
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonarray = JsonFunctions
.getJSONfromURL("http://cloud....com/broccoli/menu_typeitem.php?id=" + getIntent().getStringExtra("id"));
try {
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
map.put("name", jsonobject.getString("name"));
map.put("image", jsonobject.getString("image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.list1);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(SubMenu.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
listview.setOnItemClickListener(this);
}
}
In if condition write this.
if( name.getText().toString().equals("Bian‌​‌​ca Pizza")){
}else{
Toast.makeText(SubMenu.this, "hello", Toast.LENGTH_SHORT).show();
}
or
if( name.getText().toString().matches("Bian‌​‌​ca Pizza")){
}else{
Toast.makeText(SubMenu.this, "hello", Toast.LENGTH_SHORT).show();
}

android- Dynamically add more items to custom gridview json

I have a gridview on my activity ,I get data via json and add them to my adapter .
this is the code:
gridView = (GridView) findViewById(R.id.gridView);
contactList = new ArrayList<HashMap<String, String>>();
new GetContacts().execute();
private class GetContacts extends AsyncTask<Void, Void,ArrayList<HashMap<String, String>>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
Spots_tab1_json sh = new Spots_tab1_json();
String jsonStr = sh.makeServiceCall(url+page, Spots_tab1_json.GET);
ArrayList<HashMap<String, String>> dataC = new ArrayList<HashMap<String, String>>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
if(contacts.length()<20)
loadmore=false;
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
HashMap<String, String> contact = new HashMap<String, String>();
contact.put("id", new String(c.getString("id").getBytes("ISO-8859-1"), "UTF-8"));
contact.put("url", new String(c.getString("url").getBytes("ISO-8859-1"), "UTF-8"));
contact.put("text", new String(c.getString("text").getBytes("ISO-8859-1"), "UTF-8"));
dataC.add(contact);
}
} catch (JSONException e) {
goterr=true;
} catch (UnsupportedEncodingException e) {
goterr=true;
}
} else {
Log.v("this","mi;;");
goterr=true;
}
return dataC;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
if(!isCancelled() && goterr==false){
if(ladap==null){
ladap=new ListAdapter(FistActiivty.this,result);
gridView.setAdapter(ladap);
}else{
ladap.addAll(result);
}
}else{
MyToast.makeText(FistActiivty.this, DariGlyphUtils.reshapeText(getResources().getString(R.string.problemload)));
}
}
}
public class ListAdapter extends BaseAdapter {
Activity activity;
public ArrayList<HashMap<String,String>> list;
public ListAdapter(Activity activity, ArrayList<HashMap<String, String>>list ) {
super();
this.activity=FistActiivty.this;
this.list=list;
}
public HashMap<String, String> geting(int position) {
return list.get(position);
}
public void addAll(ArrayList<HashMap<String, String>> result) {
if(this.list==null){
//this.list = new ArrayList<HashMap<String, String>>();
this.list =result;
}else{
this.list.addAll(result);
}
//list.addAll(result);
notifyDataSetChanged();
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return list.get(position);
}
public long getItemId(int arg0) {
return 0;
}
private class ViewHolder {
TextView Message;
ImageView img ;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.row_grid, null);
holder = new ViewHolder();
holder.Message = (TextView) convertView.findViewById(R.id.text);
holder.Message.setTypeface(typeface);
holder.img=(ImageView)convertView.findViewById(R.id.image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
item = list.get(position);
String text = item.get("text");
Log.v("this","11"+ text);
holder.Message.setText(text);
String imgurl = item.get("url");
if(imgurl.length()>5)
imageLoader.displayImage(imgurl, holder.img,options, imageListener);
else
holder.img.setImageDrawable(getResources().getDrawable(R.drawable.noimage));
return convertView;
}
ok , at this step, I get data from internet via json , post it to ListAdapter and add them to my gridview and no problem .
in listview ,we can add ask for more data when we reach at the bottom of listview , But how can I call function to add more items whwen I reach at the end of gridview ?
The best way to implement this is via using PullToRefreshLibrary here. Import that library to your workspace and implement setOnRefreshListener with onPullUpToRefresh. This will indicate the end of the list. You can set a request to the server to get more data to view when the end of the list is reached.
On the server, you can implement pagination to load the next set of data every time you reach the end of the list.
I hope this will help you.

android send data in listview to server

I retrieved some data from server and populated these data into a listview. I want to use part of the data i received and send it back to server. How do I do it? When I click on one of the list item it will start another activity with buttons, when i click one of the button the app will use part of the data in that listitem(which was previously retrieved from server) and send it back to server. I'm new to android programming, i'm stuck and have no idea how do I do this. Could someone advised me? I know how to send data to server by manually typing the data i want to send.
This is how i get the data from server and populated into a listview and i want to send a particular phonenumber received back to server when i click that listview item:
public class TabActivityQueue extends Fragment {
ListView list;
TextView number;
TextView info;
TextView remark;
TextView statuss;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://172.22.85.235:8080/Qproject/servlet/Qaction?action_flag=find";
//JSON Node Names
private static final String Table2 = "table2";
private static final String phonenumber = "phonenumber";
private static final String peoplenumber = "peoplenumber";
private static final String remarks = "remarks";
private static final String status = "status";
JSONArray table2 = null;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//This layout contains your list view
View view = inflater.inflate(R.layout.activity_tab_activity_queue, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)getView().findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
public ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
number = (TextView)getView().findViewById(R.id.number);
info = (TextView)getView().findViewById(R.id.info);
remark = (TextView)getView().findViewById(R.id.remark);
statuss = (TextView)getView().findViewById(R.id.statuss);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
public JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
public void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
table2 = json.getJSONArray(Table2);
for(int i = 0; i < table2.length(); i++){
JSONObject c = table2.getJSONObject(i);
// Storing JSON item in a Variable
String number = c.getString(phonenumber);
String info = c.getString(peoplenumber);
String remark = c.getString(remarks);
String statuss = c.getString(status);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(phonenumber, number);
map.put(peoplenumber, info);
map.put(remarks, remark);
map.put(status, statuss);
oslist.add(map);
list=(ListView)getView().findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.list_view,
new String[] { phonenumber,peoplenumber, remarks,status }, new int[] {
R.id.number,R.id.info, R.id.remark,R.id.statuss});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Toast.makeText(getActivity(), "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
Intent ThreeButton = new Intent(getActivity(), ThreeButton.class);
startActivity(ThreeButton);
}
}
);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent ThreeButton = new Intent(getActivity(), ThreeButton.class);
ThreeButton.putExtra("phone", oslist.get(position).get("phonenumber"));
//u can put all variables similarly...
startActivity(ThreeButton);
}
}
);
In ThreeButton Activity
onCreate(){
Intent data=getIntent();
data.getString("phone");
Log.v("phone",phone);
}
You do not have access to data in listview in your next activity. Instead of trying get that from there, you can pass needed data to new activity. Before call startActivity put into intent data using methods putExtra. By the way, if you are working with JSON you should check Gson library to parse json

Android Spinner from JSON

In my new Android app I have a view with a ListView populated from a JSON call, that is working. But what I need now is a Spinner populated with the same data as the ListView.
But after two days trying to do it, I am not able. The new Spinner id in its layout XML file is spinner2. Spinner1 is populated from a String[] as you can see in the code.
public class HiScreen extends ListActivity {
String[] spinnerValues = { "1","2","3"};
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> newsList;
// url to get all products list
private static String url_all_news = "";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_NEWS = "news";
private static final String TAG_ID = "id";
private static final String TAG_HEADER = "header";
private static final String TAG_BODY = "body";
private static final String TAG_TIME = "time";
// products JSONArray
JSONArray news = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_news);
Spinner mySpinner = (Spinner) findViewById(R.id.spinner1);
mySpinner.setAdapter(new MyAdapter(this, R.layout.custom_spinner,
spinnerValues));
Spinner s = (Spinner) findViewById( R.id.spinner2 );
String user,server_url;
Bundle extras = getIntent().getExtras();
// Obtenemos datos enviados en el intent.
if (extras != null) {
user = extras.getString("user");//usuario
server_url = extras.getString("server");
url_all_news = server_url+"android_get_all_news.php";
} else {
user="error";
}
// Hashmap for ListView
newsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
;
}
public class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context ctx, int txtViewResourceId, String[] objects) {
super(ctx, txtViewResourceId, objects);
}
#Override
public View getDropDownView(int position, View cnvtView, ViewGroup prnt) {
return getCustomView(position, cnvtView, prnt);
}
#Override
public View getView(int pos, View cnvtView, ViewGroup prnt) {
return getCustomView(pos, cnvtView, prnt);
}
public View getCustomView(int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View mySpinner = inflater.inflate(R.layout.custom_spinner, parent,
false);
TextView main_text = (TextView) mySpinner .findViewById(R.id.text_main_seen);
main_text.setText(spinnerValues[position]);
TextView subSpinner = (TextView) mySpinner
.findViewById(R.id.sub_text_seen);
subSpinner.setText(spinnerSubs[position]);
ImageView left_icon = (ImageView) mySpinner
.findViewById(R.id.left_pic);
left_icon.setImageResource(total_images[position]);
return mySpinner;
}
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(HiScreen.this);
pDialog.setMessage("Loading News. Bitte warten...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_news, "GET", params);
// Check your log cat for JSON reponse
Log.d("All News: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
news = json.getJSONArray(TAG_NEWS);
String[] datos = new String[news.length()];
// looping through All Products
for (int i = 0; i < news.length(); i++) {
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
datos[i] = c.getString(TAG_HEADER);
String id = c.getString(TAG_ID);
String header = c.getString(TAG_HEADER);
String body = c.getString(TAG_BODY);
String time = c.getString(TAG_TIME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_HEADER, header);
map.put(TAG_BODY, body);
map.put(TAG_TIME, time);
// adding HashList to ArrayList
newsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
HiScreen.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
HiScreen.this, newsList,
R.layout.list_item, new String[] { TAG_ID,
TAG_HEADER,TAG_BODY,TAG_TIME},
new int[] { R.id.pid, R.id.name,R.id.body,R.id.time });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
You can create String Array or ArrayList from json, after it you can add it in array adapter so you can easily add data to spinner.

footer view not displayed in listview (Custom adapter)

Footer view is not displayed at the end of the listview .
Pleas tell me where I am going wrong .The code for the footerview is :
footerView = ((LayoutInflater)getBaseContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.listfooter, null, false);
list.addFooterView(footerView);
footerView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
Entire Code :
public class CustomizedListView extends Activity {
// All static variables
static final String URL = "https://itunes.apple.com/us/rss/topalbums/limit=20/json";
// XML node keys
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";
static ListView list;
static LazyAdapter adapter;
HashMap<String, String> map;
public static String message_receiver_str;
public static int deleteposition;
public static ArrayList<HashMap<String, String>> songsList;
View footerView ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
songsList = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL(URL);
try {
JSONObject arr2 = json.getJSONObject("feed");
JSONArray arr = arr2.getJSONArray("entry");
for (int i = 0; i < arr.length(); i++) {
JSONObject e1 = arr.getJSONObject(i);
JSONArray arr3 = e1.getJSONArray("im:image");
JSONObject arr8 = e1.getJSONObject("im:name");
JSONObject arr10 = e1.getJSONObject("im:artist");
JSONObject e12 = arr3.getJSONObject(0);
// creating new HashMap
map = new HashMap<String, String>();
map.put(KEY_THUMB_URL, e12.getString("label"));
map.put(KEY_ARTIST, arr8.getString("label"));
map.put(KEY_TITLE, arr10.getString("label"));
// adding HashList to ArrayList
songsList.add(map);
}
} catch (JSONException e) {
// Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getBaseContext(),
"Network communication error!", 5).show();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o= (HashMap<String, String>) list.getItemAtPosition(position);
// Toast.makeText(CustomizedListView.this, "ID '" + o.get("title") + "' was clicked.", Toast.LENGTH_SHORT).show();
deleteposition=position;
message_receiver_str= o.get("title");
Intent ii= new Intent(getBaseContext(),openedmsg.class);
startActivity(ii);
}
});
footerView = ((LayoutInflater)getBaseContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.listfooter, null, false);
list.addFooterView(footerView);
footerView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
}
LazyAdapter.java
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data=new ArrayList<HashMap<String, String>>();
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public static HashMap<String, String> song;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
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.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
song = new HashMap<String, String>();
song = data.get(position);
// Setting all values in listview
title.setText(song.get(CustomizedListView.KEY_TITLE));
artist.setText(song.get(CustomizedListView.KEY_ARTIST));
duration.setText(song.get(CustomizedListView.KEY_DURATION));
imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image);
return vi;
}
}
listfooter.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:gravity="center_horizontal"
android:padding="13dp"
android:layout_height="fill_parent">
<TextView
android:id="#id/android:empty"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center"
android:padding="15dp"
android:text="Tap to Load"
android:textColor="#android:color/darker_gray"/>
</LinearLayout>
You must call addFooterView() before you call setAdapter() on the ListView. Same applies for addHeaderView().

Categories

Resources