I have a tab host that loads following file into one of the tabs
package com.api.view;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import com.api.api.api;
import com.api.app.R;
import com.api.communication.reports;
import com.api.sync.data.reportsList;
import com.api.tools.serverCommunication;
import com.api.tools.urlbuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class EquipmentTabHistory extends Activity{
ListView lv;
ListViewAdapter adapter;
ArrayList<HashMap<String, String>> menuItems;
ProgressDialog pDialog;
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
private class ListViewAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater=null;
public ListViewAdapter(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 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_item, null);
TextView name = (TextView)vi.findViewById(R.id.name);
HashMap<String, String> item = new HashMap<String, String>();
item = data.get(position);
//Setting all values in listview
name.setText(item.get("name"));
return vi;
}
}
private class loadMoreListView extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... unused) {
try {
reportsList al;
int eid = Integer.parseInt(getIntent().getStringExtra("eid"));
String[][] surl = new String[1][2];
surl[0][0] = "eid";
surl[0][1] = ""+eid;
String url;
url = urlbuilder.buildurl("getEquipmentHistory", surl);
api.debug("com.api.view.EquipmentTabHistory","URL: "+url,"info");
String pull = serverCommunication.pull(url);
reports reports;
reports = new reports(pull);
for(int i=0;i<reports.getList().size();i++){
al = reports.getList().get(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_ID,reports.getList().get(i).did);
long timestamp = Integer.parseInt(al.date) * 1000; // msec
java.util.Date d = new java.util.Date(timestamp);
map.put(KEY_NAME,al.ReportId + " - "+al.Typ + " - " + al.description + "("+d.getMonth()+". "+cT(d.getDay())+" "+(1900 + d.getYear())+" - "+d.getHours()+":"+cT(d.getMinutes())+")");
menuItems.add(map);
}
} catch (Exception e) {
api.debug("com.api.view.EquipmentTabHistory","NSAE: "+e.getMessage(),"error");
}
return (null);
}
private String cT(int time){
String r = "";
r += (time>9)?time:(time>0)?"0"+time:time;
return r;
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.api_tab_history);
lv = (ListView) findViewById(R.id.listViewEquipment);
menuItems = new ArrayList<HashMap<String, String>>();
adapter = new ListViewAdapter(this, menuItems);
lv.setAdapter(adapter);
new loadMoreListView().execute();
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
api.debug("com.api.view.EquipmentTabHistory","Clicked: "+arg2+"-"+arg3,"warn");
api.debug("com.api.view.EquipmentTabHistory","Clicked: "+((TextView)findViewById(R.id.name)).getText().toString(),"warn");
api.debug("com.api.view.EquipmentTabHistory","Selected: "+menuItems.get(arg2).get(KEY_ID),"warn");
String[][] surl = new String[2][2];
surl[0][0] = "did";
surl[0][1] = menuItems.get(arg2).get(KEY_ID);
surl[1][0] = "eid";
surl[1][1] = getIntent().getStringExtra("eid");
String docurl;
try {
docurl = urlbuilder.buildurlNoXml("getDocument",surl,true);
api.debug(com.api.view.EquipmentTabHistory.class.toString(),"URL: "+docurl,"info");
System.out.println(docurl);
Intent browser = new Intent(Intent.ACTION_VIEW , Uri.parse( docurl ) );
startActivity(browser);
} catch (NoSuchAlgorithmException e) {
api.debug("com.api.view.EquipmentTabHistory","No Such Algorithm "+e.getMessage(),"error");
}
}
});
}
}
The page loads without any exceptions.
In the log (through api.debug) I can see that the file is loaded and also that it get's parsed.
But I have to switch the tabs to see the changes.
How should I modify the code that it refreshes the listview as soon as the async method stops to load?
You have to override another method onPostExecute() inside AsyncTask like this:
#Override
protected Void onPostExecute(Void... unused) {
adpater.notifyDatasetChanged(); // will tell the adapter to refresh itself
}
Related
my name ari.. i am newbie in Android development. maybe you can help me to answer my problem. I want to display data from the listview adapter, but when i click the data. my app force close.
i have a adapter for show data in listview like :
ListAdapter.java
package com.santosa.sapasantosa.components;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.santosa.sapasantosa.R;
import java.util.ArrayList;
/**
* Created by muhammadaa on 10/14/2017.
*/
public class ListAdapter extends BaseAdapter {
private Activity activity;
private static ArrayList nik;
private static ArrayList nama;
private static ArrayList email;
private static ArrayList phone;
private static ArrayList jabatan;
private static ArrayList departement;
private static ArrayList gender;
private static ArrayList status;
private static ArrayList label;
private static LayoutInflater inflater = null;
public ListAdapter(Activity a, ArrayList b, ArrayList c, ArrayList d, ArrayList e, ArrayList f, ArrayList g, ArrayList h, ArrayList i, ArrayList j) {
activity = a;
this.nik = b;
this.nama = c;
this.email = d;
this.gender = e;
this.status = f;
this.label = g;
this.phone = h;
this.jabatan = i;
this.departement = j;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return nik.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.listview_data_profile, null);
TextView nik2 = (TextView) vi.findViewById(R.id.profNik); // nik
String ambilNik = nik.get(position).toString();
nik2.setText(ambilNik);
TextView nama2 = (TextView) vi.findViewById(R.id.profNama); // nama
String ambilNama = nama.get(position).toString();
nama2.setText(ambilNama);
TextView email2 = (TextView) vi.findViewById(R.id.profEmail); // email
String ambilEmail = email.get(position).toString();
email2.setText(ambilEmail);
TextView phone2 = (TextView) vi.findViewById(R.id.profPhone); // phone
String ambilPhone = phone.get(position).toString();
phone2.setText(ambilPhone);
TextView gender2 = (TextView) vi.findViewById(R.id.profGender); // gender
String ambilGender = gender.get(position).toString();
gender2.setText(ambilGender);
TextView bagian = (TextView) vi.findViewById(R.id.profBagian); // Bagian
String ambilJabatan = jabatan.get(position).toString();
String ambilDepartement = departement.get(position).toString();
bagian.setText(ambilJabatan+"/"+ambilDepartement);
TextView status2 = (TextView) vi.findViewById(R.id.profStatus); // status
String ambilStatus = status.get(position).toString();
status2.setText(ambilStatus);
TextView label2 = (TextView) vi.findViewById(R.id.countNumber); // label
String ambilLabel = label.get(position).toString();
label2.setText(ambilLabel);
return vi;
}
}
And this class fragment for using adapter
AdminHomeFragment
package com.santosa.sapasantosa.view.admin;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StringDef;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.santosa.sapasantosa.R;
import com.santosa.sapasantosa.components.ListAdapter;
import com.santosa.sapasantosa.components.RequestHandler;
import com.santosa.sapasantosa.components.SharedPrefManager;
import com.santosa.sapasantosa.configs.Constrant;
import com.santosa.sapasantosa.models.Employee;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import static android.provider.AlarmClock.EXTRA_MESSAGE;
/**
* A simple {#link Fragment} subclass.
*/
public class AdminHomeFragment extends Fragment {
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
ArrayList<String> nik_array = new ArrayList<String>();
ArrayList<String> nama_array = new ArrayList<String>();
ArrayList<String> email_array = new ArrayList<String>();
ArrayList<String> phone_array = new ArrayList<String>();
ArrayList<String> gender_array = new ArrayList<String>();
ArrayList<String> jabatan_array = new ArrayList<String>();
ArrayList<String> departement_array = new ArrayList<String>();
ArrayList<String> status_array = new ArrayList<String>();
ArrayList<Integer> label_array = new ArrayList<>();
com.santosa.sapasantosa.components.ListAdapter adapter;
ListView listPeg;
public AdminHomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_admin_home, container, false);
listPeg = (ListView) view.findViewById(R.id.pegListView);
listPeg.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getActivity(),ProfileEmployeeActivity.class);
HashMap<String,String> map = (HashMap) parent.getItemAtPosition(position);
Log.e("","adad "+map);
String empId = map.get("nik");
i.putExtra("nik",empId);
startActivity(i);
}
});
loadDataPegawai();
return view;
}
private void loadDataPegawai() {
// get parameter
final String users = SharedPrefManager.getInstance(getContext()).getUserEmployee().getNik();
class LoadPegawai extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("username", users);
//returing the response
return requestHandler.sendPostRequest(Constrant.URL_PROFIL, params);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
int n = 1;
try {
JSONObject obj = new JSONObject(s);
if (!obj.getBoolean("error")) {
// get data user dari respone
JSONArray userJson = obj.getJSONArray("user");
for (int i = 0, count = userJson.length(); i < count; i++) {
try {
JSONObject jsonObject = userJson.getJSONObject(i);
if (jsonObject.getString("employeeStatus").toString().equals("0")) {
nik_array.add(jsonObject.getString("employeeID").toString());
nama_array.add(jsonObject.getString("employeeNama").toString());
email_array.add(jsonObject.getString("employeeEmail").toString());
gender_array.add(jsonObject.getString("employeeGender").toString());
status_array.add(jsonObject.getString("employeeStatus").toString());
phone_array.add(jsonObject.getString("employeePhone").toString());
jabatan_array.add(jsonObject.getString("employeeJabatan").toString());
departement_array.add(jsonObject.getString("employeeDepartement").toString());
label_array.add(n++);
String id = jsonObject.getString("employeeID").toString();
// adding to hashmap
HashMap<String,String> employees = new HashMap<>();
employees.put("nik",id);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/* Set data to listview */
adapter = new com.santosa.sapasantosa.components.ListAdapter( getActivity(),
nik_array,
nama_array,
email_array,
gender_array,
status_array,
label_array,
phone_array,
jabatan_array,
departement_array);
listPeg.setAdapter(adapter);
listPeg.setTextFilterEnabled(true);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
//executing the async task
LoadPegawai ru = new LoadPegawai();
ru.execute();
}
}
when i clik data adapter in ListView, i have a Error like:
Can you help me for resolve the error. I say very very thanks you for your help...
Seems you're trying to display all employees as a ListView... If my understanding is't wrong, you should :
Create an EmployeeBean
Put all your employee into a collection...maybe ArrayList.
After that, when you click an item on ListView, the integer you get is the index of EmployeeBean in your collection, so that you can access it from your collection.
package com.thesoft.smsdemo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
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.R.integer;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.thesoft.smsdemo.JSONParser;
public class Upload extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
new Hi().execute();
}
private class Hi extends AsyncTask<String, Void, String> {
ProgressDialog rDialog;
JSONParser lv = new JSONParser();
ListView vti ;
public HashMap<Integer, HashMap<String, String>> notes_data = new HashMap<Integer, HashMap<String, String>>();
#Override
protected void onPreExecute() {
super.onPreExecute();
rDialog = new ProgressDialog(Upload.this);
rDialog.setMessage("Fetching Data From Server..");
rDialog.setIndeterminate(false);
rDialog.setCancelable(false);
rDialog.show();
}
#Override
protected String doInBackground(String... sam) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("co_name", "All"));
return lv.makeHttpRequest(
"+++++URL Link++++++++",
"GET", params);
}
#Override
protected void onPostExecute(String result) {
Log.d("value", result);
String name = "", head = "", desb = "", date = "";
JSONArray jsArray;
try {
jsArray = new JSONArray(result);
Log.d("json arry", "" + jsArray.length());
for (int j = 0; j < jsArray.length(); j++) {
HashMap<String, String> data = new HashMap<String, String>();
JSONObject jobj = jsArray.getJSONObject(j);
data.put("co_name", jobj.getString("co_name").toString());
data.put("head", jobj.getString("head").toString());
data.put("desb", jobj.getString("desb").toString());
data.put("date", jobj.getString("date").toString());
Log.d("valuesss",j+"");
notes_data.put(j, data);
Log.d("name",jobj.getString("co_name").toString());
Log.d("name",jobj.getString("head").toString());
Log.d("name",jobj.getString("date").toString());
}
/*String[] notes_da = {"hjhkh","hggg","hghgghgh"};
for (int i = 0; i < notes_da.length; i++) {
notes_da[i] = "Notes " + i;
}*/
MySimpleArrayAdapter mr = new MySimpleArrayAdapter(getApplicationContext(), notes_data);
/* ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.custom_list, R.id.tv, notes_da);
*/ vti=(ListView)findViewById(R.id.li1);
vti.setAdapter(mr);
} catch (JSONException e) {
e.printStackTrace();
} finally {
rDialog.dismiss();
Log.d("valuesss",notes_data.get(3).get("head"));
}
}
}
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
HashMap<Integer, HashMap<String, String>> data = new HashMap<Integer, HashMap<String, String>>();
public MySimpleArrayAdapter(Context context, HashMap<Integer, HashMap<String, String>> data) {
super(context, R.layout.custom_list);
this.context = context;
this.data = data;
}
#SuppressLint("ViewHolder")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater
.inflate(R.layout.custom_list, parent);
TextView textView = (TextView) convertView.findViewById(R.id.tv);
TextView des = (TextView) convertView.findViewById(R.id.t2);
TextView date = (TextView) convertView.findViewById(R.id.textView1);
// change the icon for Windows and iPhone
String head = data.get(position).get("head");
String desb = data.get(position).get("desb");
String date1 = data.get(position).get("date");
textView.setText(head);
des.setText(desb);
date.setText(date1);
return convertView;
}
}
}
The data is fetched but not able to set it on custom Adapter for Listview
the data can be seen in log cat but the list activity is not shown on the device. Please Help me with this code Thanks
The data is fetched but not able to set it on custom Adapter for Listview
the data can be seen in log cat but the list activity is not shown on the device. Please Help me with this code Thanks
There are a couple of things you are missing:
Inside getView(...)
convertView = inflater.inflate(R.layout.custom_list, parent);
It should be inflater.inflate(R.layout.custom_list, null);
#param root Optional view to be the parent of the generated hierarchy.
public View inflate(int resource, ViewGroup root)
You have to override getCount in your custom adapter
#Override
public int getCount() {
return data.size();
}
where data = new HashMap>();
Additionally, its better to reuse cells in getView of your custom adapter. For this purpose you could use ViewHolder.
If not helpful, please share your layout xmls.
I am trying to parse the images and text from url to list view.
I succesfully parse names but unable to parse Images. I follow these links....
I am getting bit map value null in image loader class..
I copied the MemoryCache and File Cache classes from the below links... Is there any mistake in my code?
My Json is: http://192.185.159.159/~charmmar/raj_spice/webservices/index.php?action=products
Is any problem for image parsing if json is large?
http://www.androidbegin.com/tutorial/android-json-parse-images-and-texts-tutorial/
http://luchfilip.wordpress.com/2014/02/25/android-how-to-parse-json-and-show-images-and-texts-in-a-listview/comment-page-1/
http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/
in these links all contained ImageLoader, FileCache, MemoryCache classes but I am unable to parse images... is any special library needed for this?
My class:
package com.example.dellizia;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ListView;
public class RecipesJson extends Helper {
private String url = com.example.dellizia.Utility.urlpath + "products";
ArrayList<HashMap<String, String>> productList;
ProgressDialog pdialog;
final String TAG_DATA = "data";
final String TAG_ID = "id";
final static String TAG_NAME = "name";
final static String TAG_IMAGE = "images";
ListView listview;
RecipeJsonAdapter adapter;
SharedPreferences preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
PrefEdit("pref__footer", "img_recipe");
footerBlock();
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
pdialog = new ProgressDialog(RecipesJson.this);
// Set progressdialog title
// pdialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
pdialog.setMessage("Loading...");
pdialog.setIndeterminate(false);
// Show progressdialog
pdialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
productList = new ArrayList<HashMap<String, String>>();
try {
String res = JsonFunction.getJSONfromURL(url);
Log.e("","resvalue--------"+res);
JSONObject jsonobj = new JSONObject(res);
String id = jsonobj.getString("status");
Log.e("","id value in parse json--------"+id);
if (id.equals("1")) {
JSONArray userdata = jsonobj.getJSONArray("data");
for (int i = 0; i < userdata.length(); i++) {
HashMap<String, String> pdata = new HashMap<String, String>();
JSONObject obj = userdata.getJSONObject(i);
String catid = userdata.getJSONObject(i).getString("id");
String name = userdata.getJSONObject(i).getString("name");
String image = userdata.getJSONObject(i).getString("images");
pdata.put(TAG_ID, catid);
Log.e("", "TAG_ID---" + TAG_ID);
pdata.put(TAG_NAME, name);
Log.e("", "TAG_NAME---" + TAG_NAME);
Log.e("", "name---" + name);
pdata.put(TAG_IMAGE, image);
Log.e("", "TAG_IMAGE---" + TAG_IMAGE);
Log.e("", "image-----------" + image);
productList.add(pdata);
Log.e("", "product list----" + productList);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.recipeslist);
// Pass the results into ListViewAdapter.java
adapter = new RecipeJsonAdapter(RecipesJson.this, productList);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
pdialog.dismiss();
}
}
}
My adapter class:
package com.example.dellizia;
import java.util.ArrayList;
import java.util.HashMap;
import com.example.androidhive.ImageLoader;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class RecipeJsonAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public RecipeJsonAdapter(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.recipeitems, 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.recipeimage); // thumb image
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
// Setting all values in listview
Log.e("","names values ------------"+song.get(RecipesJson.TAG_NAME));
title.setText(song.get(RecipesJson.TAG_NAME));
//artist.setText(song.get(CustomizedListView.KEY_ARTIST));
// duration.setText(song.get(CustomizedListView.KEY_DURATION));
Log.e("","images values ------------"+song.get(RecipesJson.TAG_IMAGE));
imageLoader.DisplayImage(song.get(RecipesJson.TAG_IMAGE), thumb_image);
return vi;
}
}
This is my link for all classes.. http://ge.tt/8keNUh62?c. In this link all my used classes are available.
Please help!
I need help implementing my app. There are different activities. On one activity, a list view is shown, then if the user clicks on a row, another list view activity is shown.
The list view activities may need a variable that is used as param to a URL to retrieve JSON data to feed the list view. I will try to explain it better.
Activity 1: ListView with objects retrieve from JSON (no need for URL param). User clicks on row and opens Activity 2 ( a variable is passed from activity 1 to activity 2).
Activity 2: ListView with objects retrieve from JSON, URL includes param (variable passed from A1 to A2). List view objects are shown.
Now the user clicks on back button (hardware button). Activity 1 list view objects shown.
If the user clicks again on the same row at A1 as before, then A2 doesn't show anything.
If you need me to show my code, no problem...but I need more an explanation to the behaviour rather than code examples. Thank you
EDIT HERE:
ACTIVITY 1 LISTVIEW ADAPTER
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class DondeEsta_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 DondeEsta_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_categoria_donde_esta_textView;
TextView nombre_categoria_donde_esta_textView;
ImageView imagen_categoria_donde_esta;
TextView tipo_menu;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.dondeesta_listview_item, parent, false);
// Get the position
resultp = data.get(position);
RelativeLayout myLayout = (RelativeLayout) itemView.findViewById(R.id.milayout);
if (position % 2 == 1) {
myLayout.setBackgroundResource(R.color.fondo);
//lugar_evento.setBackgroundResource(R.color.fondo);
} else {
myLayout.setBackgroundResource(R.color.blanco);
//titulo_evento.setBackgroundResource(R.color.blanco);
//lugar_evento.setBackgroundResource(R.color.blanco);
}
String tipo_de_menu = resultp.get(DondeEsta_MainActivity.TIPO_MENU);
String id_categoria_donde_esta =resultp.get(DondeEsta_MainActivity.ID_CATEGORIA_DONDE_ESTA);
// Locate the TextViews in listview_item.xml
nombre_categoria_donde_esta_textView = (TextView) itemView.findViewById(R.id.textView1);
imagen_categoria_donde_esta = (ImageView) itemView.findViewById(R.id.imageView1);
nombre_categoria_donde_esta_textView.setText (resultp.get(DondeEsta_MainActivity.NOMBRE_CATEGORIA_DONDE_ESTA));
imageLoader.DisplayImage(resultp.get(DondeEsta_MainActivity.IMAGEN_CATEGORIA_DONDE_ESTA), imagen_categoria_donde_esta);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
String tipo_de_menu = resultp.get(DondeEsta_MainActivity.TIPO_MENU);
Log.i("TIPO DE MENU =", tipo_de_menu);
if (tipo_de_menu.equals("1")){
Log.i("PULSADO =", tipo_de_menu);
//TIPO 1
String idPrueba = resultp.get(DondeEsta_MainActivity.ID_CATEGORIA_DONDE_ESTA);
System.out.println("la id en DONDEESTA_LV ANTES DE PASARLA A T1 ++++++++++++++++++ ES: " + idPrueba);
Intent intent = new Intent(context, DondeEsta_T1_MainActivity.class);
intent.putExtra("idPrueba", idPrueba);
context.startActivity(intent);
}
else
//TIPO 2
if (tipo_de_menu.equals("2")){
Log.i("PULSADO =", tipo_de_menu);
//TIPO 2
String idPrueba = resultp.get(DondeEsta_MainActivity.ID_CATEGORIA_DONDE_ESTA);
System.out.println("la id en DONDEESTA_LV ANTES DE PASARLA A T1 ++++++++++++++++++ ES: " + idPrueba);
Intent intent = new Intent(context, DondeEsta_T2_MainActivity.class);
intent.putExtra("idPrueba", idPrueba);
context.startActivity(intent);
}
else {
Intent intent = new Intent(context, DondeEsta_SingleItemView.class);
}
}
});
return itemView;
}
}
ACTIVITY 2 MAIN ACTIVITY
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
public class DondeEsta_T1_MainActivity extends Activity {
// Declare Variables
private static final String TAG_NAME = "nombreCategoria";
private static final String TAG_ID = "idPrueba";
private String name = "Categoria";
private String id = "id";
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
DondeEsta_T1_ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String ID_DES= "id_des";
static String TITULO_DES = "titulo_des";
static String CATEGORIAS_DES = "categoria_des";
static String LUGAR_DES = "lugar_des";
static String LATITUD_DES = "latitud_des";
static String LONGITUD_DES = "longitud_des";
static String IMAGEN_DES = "imagen_des";
static String DESCRIPCION_DES = "descripcion_des";
static String WEB_DES = "web_des";
static String MAIL_DES = "mail_des";
static String TEL_DES = "tel_des";
static String LUGAR_CORTO = "lugar_corto";
static String idPrueba = "idPrueba";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("MVASCO", "context is null!");
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
name = in.getStringExtra(TAG_NAME);
id = in.getStringExtra(TAG_ID);
idPrueba =in.getStringExtra(idPrueba);
setContentView(R.layout.dondeesta_t1_listview_main);
// Execute DownloadJSON AsyncTask
//new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
// Log.v("categoria para pasar a la URL", id_categoria_donde_esta);
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://..URL hidden.../casajuventud/app_php_files/recuperar_categorias_donde_esta_t1.php?cat="+idPrueba);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("Categorias");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("id_des", jsonobject.getString("id_des"));
map.put("titulo_des", jsonobject.getString("titulo_des"));
map.put("categoria_des", jsonobject.getString("categoria_des"));
map.put("lugar_des", jsonobject.getString("lugar_des"));
map.put("latitud_des", jsonobject.getString("latitud_des"));
map.put("longitud_des", jsonobject.getString("longitud_des"));
map.put("descripcion_des", jsonobject.getString("descripcion_des"));
map.put("web_des", jsonobject.getString("web_des"));
map.put("mail_des", jsonobject.getString("mail_des"));
map.put("imagen_des", "http://www.solinpromex.com/casajuventud/sitios/"+jsonobject.getString("imagen_des"));
map.put("tel_des", jsonobject.getString("tel_des"));
map.put("lugar_corto", jsonobject.getString("lugar_corto"));
// 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.listview);
// Pass the results into ListViewAdapter.java
adapter = new DondeEsta_T1_ListViewAdapter(DondeEsta_T1_MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
new DownloadJSON().execute();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
}
ACTIVITY 2 LISTVIEWADAPTER
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class DondeEsta_T1_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 DondeEsta_T1_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_des;
TextView titulo_des;
TextView categoria_des;
TextView lugar_des;
TextView latitud_des;
TextView longitud_des;
ImageView imagen_des;
TextView descripcion_des;
TextView web_des;
TextView tel_des;
TextView lugar_corto;
TextView mail_des;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.dondeesta_t1_listview_item, parent, false);
// Get the position
resultp = data.get(position);
RelativeLayout myLayout = (RelativeLayout) itemView.findViewById(R.id.milayout);
if (position % 2 == 1) {
myLayout.setBackgroundResource(R.color.fondo);
//lugar_evento.setBackgroundResource(R.color.fondo);
} else {
myLayout.setBackgroundResource(R.color.blanco);
//titulo_evento.setBackgroundResource(R.color.blanco);
//lugar_evento.setBackgroundResource(R.color.blanco);
}
String tipo_de_menu = resultp.get(DondeEsta_MainActivity.TIPO_MENU);
// Locate the TextViews in listview_item.xml
titulo_des = (TextView) itemView.findViewById(R.id.textView1);
lugar_corto = (TextView) itemView.findViewById(R.id.textView2);
titulo_des.setText (resultp.get(DondeEsta_T1_MainActivity.TITULO_DES));
lugar_corto.setText (resultp.get(DondeEsta_T1_MainActivity.LUGAR_CORTO));
// imageLoader.DisplayImage(resultp.get(DondeEsta_MainActivity.IMAGEN_CATEGORIA_DONDE_ESTA), imagen_categoria_donde_esta);
// 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, DondeEsta_T1_SingleItemView.class);
// Pass all data rank
intent.putExtra("titulo_des", resultp.get(DondeEsta_T1_MainActivity.TITULO_DES));
intent.putExtra("lugar_des", resultp.get(DondeEsta_T1_MainActivity.LUGAR_DES));
intent.putExtra("latitud_des", resultp.get(DondeEsta_T1_MainActivity.LATITUD_DES));
intent.putExtra("longitud_des", resultp.get(DondeEsta_T1_MainActivity.LONGITUD_DES));
intent.putExtra("imagen_des", resultp.get(DondeEsta_T1_MainActivity.IMAGEN_DES));
intent.putExtra("descripcion_des", resultp.get(DondeEsta_T1_MainActivity.DESCRIPCION_DES));
intent.putExtra("web_des", resultp.get(DondeEsta_T1_MainActivity.WEB_DES));
intent.putExtra("tel_des", resultp.get(DondeEsta_T1_MainActivity.TEL_DES));
intent.putExtra("mail_des", resultp.get(DondeEsta_T1_MainActivity.MAIL_DES));
intent.putExtra("lugar_corto", resultp.get(DondeEsta_T1_MainActivity.LUGAR_CORTO));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
just put
#Override
public void onBackPressed(){
finish();
}
somewhere inside second Activity.
also after idPrueba =in.getStringExtra(idPrueba); you might try in.removeExtra("idPrueba");
and the last: why idPrueba is static? code key as other variable, static final, and get your passed value to another variable. when you starting second Activity for the first time you fetching newly arrived varriable and assigning it to key variable. this value is static, so second call of Activity have previosly overwritten key (not "idPrueba", but value of previously passed variable under "idPrueba" key). probably this is your issue
for this code the easiest way is to remove static before String idPrueba = "idPrueba"; but I suggest you to separate key and value variables. also check setOnItemClickListener method, more convenient
I can't seem to figure out what is going wrong with this, the code is pretty clean/ simple, but for some reason when I pull to refresh, it just shows me the loading icon infinity. Not only that, but I don't even receive any errors. The library I used for pull to refresh is this one.
I've spent several hours trying to figure this out, but the fact that it's not even giving me errors is making it very hard for me to track down.
And yes, I am sure the rest request is working.
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
public final class PullToRefresh extends Activity {
static final int MENU_SET_MODE = 0;
static final String KEY_FEED = "feed"; // parent node
static final String KEY_UID_FK = "uid_fk";
static final String KEY_FIRST_NAME = "first_name";
static final String KEY_LAST_NAME = "last_name";
public static final String KEY_NAME = "name";
static final String KEY_MESSAGE = "message";
static final String KEY_CREATED = "created";
static final String KEY_THUMB_URL = "thumb_img";
static final String KEY_DATA = "data";
static final String KEY_HOMETOWN = "hometown";
static final String KEY_BIO = "bio";
private ArrayList<HashMap<String, String>> feedList = new ArrayList<HashMap<String, String>>();
private PullToRefreshGridView mPullRefreshGridView;
private GridView mGridView;
private GridAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ptr_grid);
mPullRefreshGridView = (PullToRefreshGridView) findViewById(R.id.pull_refresh_grid);
mGridView = mPullRefreshGridView.getRefreshableView();
// Set a listener to be invoked when the list should be refreshed.
mPullRefreshGridView
.setOnRefreshListener(new OnRefreshListener2<GridView>() {
#Override
public void onPullDownToRefresh(
PullToRefreshBase<GridView> refreshView) {
Toast.makeText(PullToRefresh.this, "Pull Down!",
Toast.LENGTH_SHORT).show();
try {
new RestClientUsage().getPublicTimeline();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onPullUpToRefresh(
PullToRefreshBase<GridView> refreshView) {
Toast.makeText(PullToRefresh.this, "Pull Up!",
Toast.LENGTH_SHORT).show();
try {
new RestClientUsage().getPublicTimeline();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
ArrayList<HashMap<String, String>> feedList = new ArrayList<HashMap<String, String>>();
TextView tv = new TextView(this);
tv.setGravity(Gravity.CENTER);
tv.setText("Empty View, Pull Down/Up to Add Items");
mPullRefreshGridView.setEmptyView(tv);
adapter = new GridAdapter(PullToRefresh.this, feedList);
mGridView.setAdapter(adapter);
}
class RestClientUsage {
public void getPublicTimeline() throws JSONException {
RequestParams params = new RequestParams();
params.put("loggedin_uid", TabHostFragmentActivity.loggedin_uid);
RestClient.post("http://localhost/basic/rest/request/format/json",
params, new JsonHttpResponseHandler() {
private JSONArray feed;
#Override
public void onSuccess(JSONObject json) {
try {
Log.i("JSON->TRAILS RESPONSE", json.toString(3));
// Getting Feed Array
feed = json.getJSONArray(KEY_FEED);
/*
* Log & Debug Code String feed_log =
* feed.toString(3); int feed_length =
* feed.length(); String string_length =
* Integer.toString(feed_length);
* Log.i("JSON PROFILE FEED RESPONSE", feed_log
* ); Log.i("JSON PROFILE FEED LENGTH",
* string_length);
*/
// looping through Feed of Updates
for (int i = 0; i < feed.length(); i++) {
JSONObject c = feed.getJSONObject(i);
String jFeedObj = c.toString(3);
Log.i("JSON FEED OBJ", jFeedObj);
// Storing each json item in variable
String uid = c.getString(KEY_UID_FK);
String first_name = c
.getString(KEY_FIRST_NAME);
String last_name = c
.getString(KEY_LAST_NAME);
String name = first_name + ' ' + last_name;
String http = "http://10.0.2.2/CI_REST_LOGIN/UPLOADS/thumbs/";
String base_url = c
.getString(KEY_THUMB_URL);
String thumb_url = http + base_url;
String message = c.getString(KEY_MESSAGE);
String created = c.getString(KEY_CREATED);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
map.put(KEY_UID_FK, uid);
map.put(KEY_NAME, name);
map.put(KEY_MESSAGE, message);
map.put(KEY_CREATED, created);
map.put(KEY_THUMB_URL, thumb_url);
Log.i("Trails - line 130", "Success");
// adding HashList to ArrayList
feedList.add(map);
}
adapter.notifyDataSetChanged();
// Call onRefreshComplete when the list has been
// refreshed.
mPullRefreshGridView.onRefreshComplete();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(
0,
MENU_SET_MODE,
0,
mPullRefreshGridView.getMode() == Mode.BOTH ? "Change to MODE_PULL_DOWN"
: "Change to MODE_PULL_BOTH");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem setModeItem = menu.findItem(MENU_SET_MODE);
setModeItem
.setTitle(mPullRefreshGridView.getMode() == Mode.BOTH ? "Change to MODE_PULL_FROM_START"
: "Change to MODE_PULL_BOTH");
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_SET_MODE:
mPullRefreshGridView
.setMode(mPullRefreshGridView.getMode() == Mode.BOTH ? Mode.PULL_FROM_START
: Mode.BOTH);
break;
}
return super.onOptionsItemSelected(item);
}
}
And here is the code for my GridView adapter:
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.loopj.android.image.SmartImageView;
public class GridAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public GridAdapter(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.mobile, null);
TextView name = (TextView) vi.findViewById(R.id.grid_item_label); // title
SmartImageView thumb_image = (SmartImageView) vi
.findViewById(R.id.grid_item_image);
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
// Setting all values in listview
name.setText(update.get("name"));
thumb_image.setImageUrl(update.get("thumb_img"));
name.setOnClickListener(new myOnClickListener(position));
thumb_image.setOnClickListener(new myOnClickListener(position));
return vi;
}
public class myOnClickListener implements OnClickListener {
private int position;
private String clicked_uid;
public myOnClickListener(int position) {
this.position = position;
}
#Override
public void onClick(View v) { // TODO Auto-generated method stub
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
Log.i("Update Position:", update.toString());
clicked_uid = update.get("uid");
Log.d("Clicked UID:", clicked_uid + "");
Intent i = new Intent(activity.getApplicationContext(),
TabHostFragmentActivity.class);
i.putExtra("profile_uid", clicked_uid);
activity.startActivity(i);
}
}
}
You should POST to 10.0.2.2 instead of localhost in the call to RestClient.post in RestClientUsage.
I am not familiar withJsonHttpResponseHandler, but I would image there's an onFailure method (or something similar) that you may want to override. If there is, you may way to call mPullRefreshGridView.onRefreshComplete() in it.