Android: SQLiteDatabase - android

I have created an SQLiteDatabase that holds information from user input. The user inputs data about their own recipe for a meal they want to share with others over facebook. This user data is stored and then displayed inside a listview. This works fine for the most part but when the listview is scrolled to observe more entries, a nullpointer occurs. I store 3 types of text information into this database but I only want the listview to display the entryID of the rows and display the rest of the information when the item is clicked.
The error message:
This is the adapter class it refers to:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class RecipeAdapter extends ArrayAdapter {
List list = new ArrayList();
public RecipeAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Recipe object) {
list.add(object);
super.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RecipeHolder recipeHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.display_entry_row,parent,false);
recipeHolder = new RecipeHolder();
recipeHolder.tx_id = (TextView)row.findViewById(R.id.t_id);
}
else{
recipeHolder = (RecipeHolder) row.getTag();
}
Recipe recipe = (Recipe)getItem(position);
recipeHolder.tx_id.setText(recipe.getId_entry().toString());
return row;
}
static class RecipeHolder{
TextView tx_id;
}
}
This is the line it is referring to:
recipeHolder.tx_id.setText(recipe.getId_entry().toString());
The Recipe Task with getter and setter:
public class Recipe {
private String id_entry;
public Recipe(String id_entry){
this.setId_entry(id_entry);
}
public String getId_entry() {
return id_entry;
}
public void setId_entry(String id_entry) {
this.id_entry = id_entry;
}
}
And if needed my background task for the database itself:
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.Toast;
public class BackgroundTask extends AsyncTask<String, Recipe, String> {
Context ctx;
RecipeAdapter mRecipeAdapter;
Activity activity;
ListView listView;
BackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity)ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String method = params[0];
DatabaseOperations dbOperations = new DatabaseOperations(ctx);
//adds information into database
if (method.equals("add_information")){
String entry = params[1];
String ingred = params [2];
String direc = params [3];
SQLiteDatabase db = dbOperations.getWritableDatabase();
dbOperations.putInformation(db, entry, ingred, direc);
return "One Row Inserted";
}
//gets information from database and places inside listview
else if (method.equals("get_info")){
listView = (ListView) activity.findViewById(R.id.listVrecipe);
SQLiteDatabase db = dbOperations.getReadableDatabase();
Cursor cursor = dbOperations.getInformation(db);
mRecipeAdapter = new RecipeAdapter(ctx,R.layout.display_entry_row);
String entry;
//loops through all row information
while (cursor.moveToNext()){
//grabs entry id
entry = cursor.getString(cursor.getColumnIndex(TableData.TableInfo.EntryID));
Recipe recipe = new Recipe(entry);
publishProgress(recipe);
}
return "get_info";
}
return null;
}
#Override
protected void onProgressUpdate(Recipe... values) {
mRecipeAdapter.add(values[0]);
}
#Override
protected void onPostExecute(String result) {
//after execution update listview with new entries
if(result.equals("get_info")){
listView.setAdapter(mRecipeAdapter);
}
else{
Toast.makeText(ctx,result, Toast.LENGTH_LONG).show();
}
}
}

As per your attached image, its states that you are getting NullPointerException at your adapters getView() method.
From my point of view, there are two possibilities.
1. RecipeHolder is null, as you did not set tag to recipeHolder by using row.setTag(recipeHolder).
2. May be Recipe object is null.
When you are using ArrayAdapter, its best practice to use this as below:
Update your RecipeAdapter as below:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class RecipeAdapter extends ArrayAdapter<Recipe> {
public RecipeAdapter(Context context, int resource, ArrayList<Recipe> list) {
super(context, resource, list);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RecipeHolder recipeHolder;
if(convertView == null){
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.display_entry_row,parent, false);
recipeHolder = new RecipeHolder();
recipeHolder.tx_id = (TextView) convertView.findViewById(R.id.t_id);
convertView.setTag(recipeHolder);
}
else{
recipeHolder = (RecipeHolder) convertView.getTag();
}
Recipe recipe = (Recipe) getItem(position);
recipeHolder.tx_id.setText(recipe.getId_entry().toString());
return row;
}
static class RecipeHolder {
TextView tx_id;
}
}
Update BackgroundTask as below:
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.Toast;
public class BackgroundTask extends AsyncTask<String, Recipe, String> {
Context ctx;
RecipeAdapter mRecipeAdapter;
Activity activity;
ListView listView;
List<Recipe> listRecipe;
BackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity)ctx;
listRecipe = new ArrayList<Recipe>();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String method = params[0];
DatabaseOperations dbOperations = new DatabaseOperations(ctx);
//adds information into database
if (method.equals("add_information")){
String entry = params[1];
String ingred = params [2];
String direc = params [3];
SQLiteDatabase db = dbOperations.getWritableDatabase();
dbOperations.putInformation(db, entry, ingred, direc);
return "One Row Inserted";
}
//gets information from database and places inside listview
else if (method.equals("get_info")){
listView = (ListView) activity.findViewById(R.id.listVrecipe);
SQLiteDatabase db = dbOperations.getReadableDatabase();
Cursor cursor = dbOperations.getInformation(db);
// Adapter
mRecipeAdapter = new RecipeAdapter(ctx, R.layout.display_entry_row, listRecipe);
String entry;
//loops through all row information
while (cursor.moveToNext()){
//grabs entry id
entry = cursor.getString(cursor.getColumnIndex(TableData.TableInfo.EntryID));
Recipe recipe = new Recipe(entry);
// Add recipe to list
listRecipe.add(recipe);
mRecipeAdapter.notifyDataSetChanged();
//publishProgress(recipe);
}
return "get_info";
}
return null;
}
#Override
protected void onProgressUpdate(Recipe... values) {
//mRecipeAdapter.add(values[0]);
}
#Override
protected void onPostExecute(String result) {
//after execution update listview with new entries
if(result.equals("get_info")){
listView.setAdapter(mRecipeAdapter);
} else {
Toast.makeText(ctx,result, Toast.LENGTH_LONG).show();
}
}
}
Hope this will help~

Related

ERROR get item in ListView when OnClick item

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.

Listview to display only one item clicked not all of the list

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

Why my listview not refresh when I press back button and come back to activity?

I'm tired already with my code. I'm writing chat application. My app consist of two activity. First activity has a listview of wich each row contain a last message which was send for the user while a second activity contain the whole conversation. In my app I used socket.io for android. My app works fine. Listview is refresh when a data is receive but when I press back button and then come back to the activity a listview not refresh itself already. In logs console I see that a data has received and "changed" method is called but listview is not refresh. What is wrong in belows code?
package com.example.seadog.fb_dialog;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
import java.util.ArrayList;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
public class MainActivity extends Activity {
public static ArrayList arrayList = new ArrayList();
public ListView listView;
public MyBaseAdapter adapter;
public TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* Get Socket.io Object
*/
SocketIO socketIo = new SocketIO();
Socket mSocket = socketIo.getSocket(); // get socket
Integer id = socketIo.getId(); // get Website ID
if(mSocket == null) {
socketIo.Connection();
mSocket = socketIo.getSocket();
mSocket.on("message", new Emitter.Listener() {
/*
* Message Listener
*/
#Override
public void call(Object... args) {
Boolean isset = false;
try {
JSONObject object = (JSONObject) args[0];
String _id = object.getString("_id");
String message = object.getString("message");
JSONObject obj = new JSONObject();
obj.put("direction", "fb-lt");
obj.put("message", message);
obj.put("date", "2017-05-29T12:15:49.245Z");
for(int i = 0; i < arrayList.size(); i++){
ListData ld = (ListData) arrayList.get(i);
String id = ld.getId();
if(_id.equals(id)){
JSONArray Data = ld.getData();
Data.put(obj);
ld.setDescription(message);
arrayList.set(i, ld);
isset = true;
Log.d("LOG", message);
}
}
if(!isset) {
JSONArray jsonArray = new JSONArray();
jsonArray.put(obj);
ListData ld = new ListData();
ld.set_id(_id);
ld.setID(1);
ld.setTitle("Klient:");
ld.setDescription(message);
ld.setData(jsonArray);
arrayList.add(ld);
}
} catch (JSONException e) {
e.printStackTrace();
}
changed();
}
});
}
/*
* Populate a listview
*/
listView = (ListView) findViewById(R.id.listView);
adapter = new MyBaseAdapter(this, arrayList);
listView.setAdapter(adapter);
/*
* OnItemClickListener
*/
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Conversation.class);
intent.putExtra("item", position);
startActivity(intent);
TextView textView = (TextView) view.findViewById(R.id.descitem);
textView.setTypeface(null, Typeface.NORMAL);
}
});
textView = (TextView) findViewById(R.id.count);
}
private void changed() {
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
Log.d("LOG:", "adapter refresh");
}
});
}
}
MyBaseAdapter Class:
package com.example.seadog.fb_dialog;
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class MyBaseAdapter extends BaseAdapter {
Context context;
ArrayList<ListData> items = new ArrayList();
LayoutInflater inflater;
int id = 0;
public MyBaseAdapter(Context context, ArrayList items) {
this.context = context;
this.items = items;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return items.size();
}
#Override
public ListData getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
ListData currentListData = getItem(position);
id = position > 0 ? getItem(position - 1).getID() : 0;
mViewHolder.Title.setText(currentListData.getTitle());
mViewHolder.Desc.setText(currentListData.getDescription());
if(1==1){
mViewHolder.Title.setVisibility(View.GONE);
}else {
if (id != currentListData.getID()) {
mViewHolder.Title.setVisibility(View.VISIBLE);
} else {
mViewHolder.Title.setVisibility(View.GONE);
}
}
return convertView;
}
private class MyViewHolder {
TextView Title, Desc;
public MyViewHolder(View item) {
Title = (TextView) item.findViewById(R.id.txtitem);
Desc = (TextView) item.findViewById(R.id.descitem);
Typeface title = Typeface.createFromAsset(context.getAssets(), "fonts/DroidSans.ttf");
Title.setTypeface(title);
Typeface desc = Typeface.createFromAsset(context.getAssets(), "fonts/DroidSans.ttf");
Desc.setTypeface(desc, Typeface.BOLD);
}
}
}
#Override
protected void onRestart() {
Intent intentBack = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intentBack);
super.onRestart();
}
you did not have any callback after you back to this activity .
You can either override onResume() method or startActivityForResult and do something in the onAcitvityForResult method.

I got "IndexOutOfBoundsException" when I try to drag down a row from my ListView (using DragSortListView)

I saw a tutorial on youtube showing how you can add data to sqlLite db and then display these data to a ListView Video.
After doing that... I applied DragSortListView to my listview... but everytime I drag a row. This error keeps on coming and I couldn't solve it :
FATAL EXCEPTION: main
Process: com.example.justi.ricksonbar, PID: 29157
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at com.example.justi.ricksonbar.ProductAdapter.getItem(ProductAdapter.java:49)
at com.example.justi.ricksonbar.BackgroundTask$1.drop(BackgroundTask.java:91)
at com.mobeta.android.dslv.DragSortListView.dropFloatView(DragSortListView.java:1501)
at com.mobeta.android.dslv.DragSortListView.access$1200(DragSortListView.java:59)
at com.mobeta.android.dslv.DragSortListView$DropAnimator.onStop(DragSortListView.java:1293)
at com.mobeta.android.dslv.DragSortListView$SmoothAnimator.run(DragSortListView.java:1192)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Here's my ProductAdapter.java¨
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.mobeta.android.dslv.DragSortController;
import com.mobeta.android.dslv.DragSortListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ProductAdapter extends ArrayAdapter{
List list = new ArrayList();
public ProductAdapter(Context context,int resource) {
super(context, resource);
}
public void add(Product object) {
list.add(object);
super.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
View row = convertView;
final ProductHolder productHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.product_list, parent, false);
productHolder = new ProductHolder();
productHolder.tx_name = (TextView)row.findViewById(R.id.tvProd_name);
productHolder.tx_price = (TextView)row.findViewById(R.id.tvProd_price);
productHolder.tx_type = (TextView)row.findViewById(R.id.tvProd_type);
row.setTag(productHolder);
}else{
productHolder = (ProductHolder) row.getTag();
}
Product product = (Product) getItem(position);
productHolder.tx_name.setText(product.getName().toString());
productHolder.tx_price.setText(Double.toString(product.getPrice()));
productHolder.tx_type.setText(product.getType().toString());
return row;
}
static class ProductHolder{
TextView tx_name, tx_price, tx_type;
}
}
and my BackgroundTask.java (where I put DragSortListView methods)
import android.app.Activity;
import android.app.VoiceInteractor;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.mobeta.android.dslv.DragSortController;
import com.mobeta.android.dslv.DragSortListView;
public class BackgroundTask extends AsyncTask<String, Product, String> {
Context ctx;
ProductAdapter productAdapter;
Activity activity;
DragSortListView listView;
BackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity)ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String method = params[0];
DatabaseHelper dHelper = new DatabaseHelper(ctx);
if (method.equals("add_info")){
String name = params[1];
double price = Double.parseDouble(params[2]);
String type = params[3];
SQLiteDatabase db = dHelper.getWritableDatabase();
//Call method of insertion
dHelper.addInformations(db, name, price, type);
return "One row is inserted....";
}else if (method.equals("get_info")){
listView = (DragSortListView)activity.findViewById(R.id.display_listview);
SQLiteDatabase db = dHelper.getReadableDatabase();
Cursor cursor = dHelper.getInformations(db);
productAdapter = new ProductAdapter(ctx,R.layout.product_list);
String name, type;
double price;
while (cursor.moveToNext()){
name = cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.NAME));
price = cursor.getDouble(cursor.getColumnIndex(ProductContract.ProductEntry.PRICE));
type = cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.TYPE));
Product product = new Product(name, price, type);
publishProgress(product);
}
return "get_info";
}
return null;
}
#Override
protected void onProgressUpdate(Product... values) {
productAdapter.add(values[0]);
}
private DragSortListView.DropListener onDrop = new DragSortListView.DropListener()
{
#Override
public void drop(int from, int to)
{
productAdapter = new ProductAdapter(ctx,R.layout.product_list);
if (from != to)
{
Object item = productAdapter.getItem(from);
productAdapter.remove(item);
productAdapter.insert(item, to);
}
}
};
private DragSortListView.RemoveListener onRemove = new DragSortListView.RemoveListener()
{
#Override
public void remove(int which)
{
productAdapter = new ProductAdapter(ctx,R.layout.product_list);
productAdapter.remove(productAdapter.getItem(which));
}
};
#Override
protected void onPostExecute(String result) {
if (result.equals("get_info")){
listView.setAdapter(productAdapter);
listView.setDropListener(onDrop);
listView.setRemoveListener(onRemove);
DragSortController controller = new DragSortController(listView);
controller.setRemoveEnabled(false);
controller.setSortEnabled(true);
controller.setDragInitMode(1);
listView.setFloatViewManager(controller);
listView.setOnTouchListener(controller);
listView.setDragEnabled(true);
}else{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
}
}
Please help me. Thank you so much
You are trying to fetch item before adding any element in a adapter.
#Override
public void drop(int from, int to)
{ // Adapter is Created here
productAdapter = new ProductAdapter(ctx,R.layout.product_list);
if (from != to)
{
// here you are trying to get item which must throw indexoutofbounds
// because you didn't added anything yet
Object item = productAdapter.getItem(from);
productAdapter.remove(item);
productAdapter.insert(item, to);
}
}
According to your add method of your adapter will add elements in Adapter.
public void add(Product object) {
list.add(object);
super.add(object);
}
Use Cursor Adapter, it is more efficient:
https://guides.codepath.com/android/Populating-a-ListView-with-a-CursorAdapter

Android : Adapter is not working with Arraylist of Hashmap

I am trying to show some data offline from SQLite database. Data is coming fine but I am not able to show that on listview with adapter.
libraryList.clear();
libraryList = dBhelper.localQuestionBank(student_uuid, questionBankId);
if (libraryList.size() > 0) {
offSetFlag = libraryList.size();
libraryListView.setAdapter(questionBankAdapter);
questionBankAdapter.notifyDataSetChanged();
libraryListView.removeFooterView(loadMoreView);
loadingMore = false;
}
localQuestionBank method:
public ArrayList<Map<String, String>> localQuestionBank(String student_uuid, String question_bank_id) {
ArrayList<Map<String, String>> localQuestionBankList = new ArrayList<>();
ArrayList<Map<String, String>> questionBankList = new ArrayList<>();
String[] columns = new String[]{QUESTION_BANK_LABEL, AIP_UUID, QUESTION_SEQUENCE_NAME, QUESTION_MARKS, DESCRIPTION};
SQLiteDatabase db = mDbHelper.getWritableDatabase();
try {
Cursor cursor = db.query(LOCAL_QUESTION_BANK, columns, STUDENT_UUID+"=?" +" and "+ QUESTION_BANK_ID+"=?", new String[] { student_uuid, question_bank_id }, null, null, null);
if (cursor.moveToFirst()) {
do {
Map<String, String> subMap = new HashMap<String, String>();
subMap.put("aep_uuid", cursor.getString(cursor.getColumnIndex(AIP_UUID)));
subMap.put("question_marks", cursor.getString(cursor.getColumnIndex(QUESTION_MARKS)));
subMap.put("question_sequence_name", cursor.getString(cursor.getColumnIndex(QUESTION_SEQUENCE_NAME)));
subMap.put("description", cursor.getString(cursor.getColumnIndex(DESCRIPTION)));
subMap.put("question_bank_label", cursor.getString(cursor.getColumnIndex(QUESTION_BANK_LABEL)));
questionBankList.add(subMap);
} while (cursor.moveToNext());
localQuestionBankList.addAll(questionBankList);
questionBankList.clear();
}
cursor.close();
db.close();
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
}
return localQuestionBankList;
}
Listview and Adapter:
questionBankAdapter = new QuestionBankAdapter(getActivity(),libraryList);
libraryListView.setAdapter(questionBankAdapter);
questionBankAdapter:
package eukti.myafterclass.adapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Map;
import eukti.myafterclass.R;
import eukti.myafterclass.ui.QuestionBankDetailsView;
import eukti.myafterclass.utils.InternetConnectionDetector;
public class QuestionBankAdapter extends BaseAdapter {
private final Activity context;
private ArrayList<Map<String, String>> dashboardList;
private static LayoutInflater inflater=null;
public QuestionBankAdapter(Activity context,
ArrayList<Map<String, String>> dashList) {
this.context = context;
this.dashboardList = dashList;
if (context!=null) {
inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
}
#Override
public int getCount() {
return dashboardList.size();
}
#Override
public Object getItem(int position) {
return dashboardList.size();
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder
{
TextView sequence;
TextView marks;
WebView description;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder=new Holder();
View rowView;
Log.d("LocalQBadapter:", dashboardList.get(position).get("question_sequence_name"));
rowView = inflater.inflate(R.layout.questionbank_items, null);
holder.sequence=(TextView) rowView.findViewById(R.id.questionSequenceName);
holder.marks=(TextView) rowView.findViewById(R.id.marks);
holder.description=(WebView) rowView.findViewById(R.id.description);
holder.description.getSettings().setJavaScriptEnabled(true);
String heading = dashboardList.get(position).get("question_sequence_name");
holder.sequence.setText(Html.fromHtml(heading));
holder.marks.setText("Marks : "+dashboardList.get(position).get("question_marks"));
String description = dashboardList.get(position).get("description");
String allAns = "<html><body>"+description.replace("\r\n", "<br/>")+"</body></html>";
holder.description.loadDataWithBaseURL(null, allAns, "text/html", "utf-8", null);
holder.description.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return true;
}
});
holder.description.setLongClickable(false);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!InternetConnectionDetector.isNetworkAvailable(context)) {
Toast.makeText(context, "Check your connection and try again.", Toast.LENGTH_LONG).show();
} else {
Intent redirect = new Intent(context, QuestionBankDetailsView.class);
redirect.putExtra("aep_uuid", dashboardList.get(position).get("aep_uuid"));
redirect.putExtra("question_sequence_name", dashboardList.get(position).get("question_sequence_name"));
redirect.putExtra("question_marks", dashboardList.get(position).get("question_marks"));
redirect.putExtra("description", dashboardList.get(position).get("description"));
context.startActivity(redirect);
}
}
});
return rowView;
}
}
It seems fine for me but data is not showing in Listview.
What you have typed
#Override
public Object getItem(int position) {
return dashboardList.size();
}
what i think it should be
#Override
public Object getItem(int position) {
return dashboardList.get(position);
}
try it and let me know
In your getItem() method you are returning the size. You need to give the actual object from the dataset dashboardList.
#Override
public Object getItem(int position) {
return dashboardList.get(position);
}
Also in the getView code you can call the getItem method instead of accessing the dataset directly.
Map<String, String> item = (Map<String, String>) getitem(position);
Bind your UI from this item object. Also try to use a Viewholder pattern in your Adapter.

Categories

Resources