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.
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.
Here is my code of the populated listview adapter that I have
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 java.util.List;
public class ListViewAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Contact> DataList;
public ListViewAdapter(Activity activity, List<Contact> dataitem) {
this.activity = activity;
this.DataList = dataitem;
}
#Override
public int getCount() {
return DataList.size();
}
#Override
public Object getItem(int location) {
return DataList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list, null);
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView companyName = (TextView) convertView.findViewById(R.id.companyName);
Contact m = DataList.get(position);
name.setText(m.getName());
companyName.setText(String.valueOf(m.getCompanyName()));
return convertView;
}
}
And here is my main
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private static final String url = "https://s3.amazonaws.com/technical-challenge/v3/contacts.json";
private List<Contact> l = new ArrayList<Contact>();
private ListView listView;
private ListViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new ListViewAdapter(this, l);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(MainActivity.this, ContactDetail.class);
startActivity(i);
}
});
JsonArrayRequest jsonreq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Contact dataSet = new Contact();
dataSet.setName(obj.getString("name"));
dataSet.setCompanyName(obj.getString("companyName"));
l.add(dataSet);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog.Builder add = new AlertDialog.Builder(MainActivity.this);
add.setMessage(error.getMessage()).setCancelable(true);
AlertDialog alert = add.create();
alert.setTitle("Error!!!");
alert.show();
}
});
Controller.getInstance(this).addToRequestQueue(jsonreq);
}
}
}
this code works properly and populates my listview, however, when I click on an item in the listview I have another listview populating that displays all contact items...I just want ONE contact item to display.
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class ListViewContactAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Contact> DataList;
public ListViewContactAdapter(Activity activity, List<Contact> dataitem) {
this.activity = activity;
this.DataList = dataitem;
}
#Override
public int getCount() {
return DataList.size();
}
#Override
public Object getItem(int location) {
return DataList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.contactlistinfo, null);
ImageView i = (ImageView) convertView.findViewById(R.id.imageView2);
TextView tv2 = (TextView) convertView.findViewById(R.id.textView2);
TextView tv4 = (TextView) convertView.findViewById(R.id.textView4);
TextView tv6 = (TextView) convertView.findViewById(R.id.textView6);
TextView tv8 = (TextView) convertView.findViewById(R.id.textView8);
TextView tv17 = (TextView) convertView.findViewById(R.id.textView17);
TextView tv18 = (TextView) convertView.findViewById(R.id.textView18);
TextView tv19 = (TextView) convertView.findViewById(R.id.textView19);
TextView tv20 = (TextView) convertView.findViewById(R.id.textView20);
TextView tv10 = (TextView) convertView.findViewById(R.id.textView10);
TextView tv12 = (TextView) convertView.findViewById(R.id.textView12);
TextView tv14 = (TextView) convertView.findViewById(R.id.textView14);
TextView tv16 = (TextView) convertView.findViewById(R.id.textView16);
Contact m = DataList.get(position);
tv2.setText(m.getName());
tv4.setText(m.getCompanyName());
tv6.setText(m.getHome());
tv12.setText(m.getMobile());
tv14.setText(m.getWork());
tv8.setText(m.getStreet());
tv18.setText(m.getCity());
tv17.setText(m.getState());
tv19.setText(m.getZipCode());
tv20.setText(m.getCountry());
tv10.setText(m.getBirthdate());
tv16.setText(m.getEmail());
i.setImageURI(Uri.parse("https://s3.amazonaws.com/technical-challenge/v3/images/elmer-fudd-small.jpg"));
return convertView;
}
}
Now here is where I have it being populated. But why does it display as another list listview? I want only ONE item.
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ContactDetail extends AppCompatActivity {
private static final String url = "https://s3.amazonaws.com/technical-challenge/v3/contacts.json";
private List<Contact> l = new ArrayList<Contact>();
private ListView listView;
private ListViewContactAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_detail);
listView = (ListView) findViewById(R.id.list2);
adapter = new ListViewContactAdapter(this, l);
listView.setAdapter(adapter);
JsonArrayRequest jsonreq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++)
try {
JSONObject obj = response.getJSONObject(i);
// Phone
JSONObject phone = obj.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
String work = phone.getString("work");
//Address
JSONObject address = obj.getJSONObject("address");
String street = address.getString("street");
String city= address.getString("city");
String state= address.getString("state");
String country= address.getString("country");
String zipCode= address.getString("zipCode");
Contact dataSet = new Contact();
dataSet.setName(obj.getString("name"));
dataSet.setCompanyName(obj.getString("companyName"));
dataSet.setBirthdate(obj.getString("birthdate"));
dataSet.setEmail(obj.getString("emailAddress"));
dataSet.setHome(home);
dataSet.setMobile(mobile);
dataSet.setWork(work);
dataSet.setStreet(street);
dataSet.setState(state);
dataSet.setCity(city);
dataSet.setZipCode(zipCode);
dataSet.setCountry(country);
dataSet.setImage(obj.getString("largeImageURL"));
l.add(dataSet);
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog.Builder add = new AlertDialog.Builder(ContactDetail.this);
add.setMessage(error.getMessage()).setCancelable(true);
AlertDialog alert = add.create();
alert.setTitle("Error!!!");
alert.show();
}
});
Controller.getInstance(this).addToRequestQueue(jsonreq);
}
}
I guess your ContactDetail activity is getting the list again. And why do you need to show a listview again if you only need one item upon clicking of one item in your first activity.
Anyway, if you still want to use listview in your ContactDetail then do this..
in your listview.setOnItemClickListener on MainActivity
Intent intent = new Intent(MainActivity.this, ContactDetail.this);
intent.putExtra("contact", l.get(position));
startActivity(intent);
in your ContactDetails activity, replace it with this.. remove that JsonArrayRequest
listView = (ListView) findViewById(R.id.list2);
Contact contact = getIntent().getSerializableExtra("contact");
l.add(contact);
adapter = new ListViewContactAdapter(this, l);
listView.setAdapter(adapter);
and also make sure that your Contact object implements Serializable
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 have an adapter that gets a list of items from an API and then puts it in a listview. This is the first time that Im working with adapters and list views and so far Im struggling quite a lot!
Why am I getting this error? Is my context wrong or something?
package com.example.tvrplayer;
import java.io.File;
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.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.TextView;
public class HiddenChannelsListAdapter extends BaseAdapter {
private Context mContext;
private ArrayList mItems;
private LayoutInflater mInflater;
public HiddenChannelsListAdapter(Context ctx, ArrayList list) {
mItems = list;
mContext = ctx;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mItems.size();
}
#Override
public HashMap getItem(int position) {
return (HashMap) mItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
System.out.println("getView " + position + " " + convertView);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.channel_item, parent, false);
} else {
((TextView) convertView.findViewById(R.id.channel_text)).setText("Testing");
}
return convertView;
}
public static class ViewHolder {
public TextView textView;
}
}
Asyntask to get the items from the server:
package com.example.tvrplayer;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
class ChannelPair {
public ListView lv;
public ArrayList channelList;
public Context ctx;
}
public class ChannelHandler extends AsyncTask<Object, Integer, ChannelPair> {
#Override
protected ChannelPair doInBackground(Object... params) {
ChannelPair p = new ChannelPair();
String apiurl = (String) params[0];
String linkid = (String) params[1];
String username = (String) params[2];
String channelID = null;
View vw = (View) params[3];
ListView lv = (ListView) vw.findViewById(R.id.list);
p.lv = lv;
JSONArray channels;
ArrayList< HashMap < String, String > > channelList = new ArrayList < HashMap < String, String > > ();
try {
channels = Json.getJson(apiurl + "/rest/channel/"+ username +"/"+ linkid, "GET");
Log.i("CHANNELS", channels.toString());
for (int i=0; i < channels.length(); i++) {
JSONObject json_data = channels.getJSONObject(i);
String name = json_data.getString("Name");
String channelid = json_data.getString("ChannelID");
HashMap<String, String> channelObject = new HashMap<String, String>();
// if ( json_data.getString("ParentPath") == "" ) {
channelObject.put("id", channelid);
channelObject.put("name", name);
channelList.add(channelObject);
// }
}
Log.i("ROOT CHANNELS", channelList.toString());
p.channelList = channelList;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return p;
}
#Override
protected void onPostExecute(final ChannelPair p) {
HiddenChannelsListAdapter adapter = new HiddenChannelsListAdapter(p.ctx, p.channelList);
p.lv.setAdapter(adapter);
}
}
The error is in this line:
HiddenChannelsListAdapter.java:28
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
The full error code:
java.lang.NullPointerException
at com.example.tvrplayer.HiddenChannelsListAdapter.<init>(HiddenChannelsListAdapter.java:28)
at com.example.tvrplayer.ChannelHandler.onPostExecute(ChannelHandler.java:71)
at com.example.tvrplayer.ChannelHandler.onPostExecute(ChannelHandler.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:602)
at android.os.AsyncTask.access$600(AsyncTask.java:156)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4514)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
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
}