Getting array of data in android from mysql json using volley - android

I am populating listview with separate item file with json string here...
item file is ticket_items
listview file is ticktsfr
Tickets.php:
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$user_id = $_GET['user_id'];
require_once('db_configuration.php');
$sql = "SELECT * FROM (SELECT a.event_name, b.ticket_name,b.ticket_quantity,
b.ticket_description, b.ticket_channel, b.ticket_start_date,
b.ticket_end_date,b.user_id FROM event a, ticket b WHERE a.event_id =
b.event_id and a.user_id = b.user_id) AS T WHERE user_id='"$user_id"'";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res))
{
array_push($result,array
(
"event_name"=>$row[0],
"ticket_name"=>$row[1],
"ticket_quantity"=>$row[2],
"ticket_description"=>$row[3],
"ticket_channel"=>$row[4],
"ticket_start_date"=>$row[5],
"ticket_end_date"=>$row[6],
"user_id"=>$row[7]
)
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
Tickets.java:(Activity)
public class Tickets extends Fragment {
//boolean variable to check user is logged in or not
//initially it is false
boolean loggedIn = false;
private ListView listView;
private static final String JSON_URL =
"http://myip/eevento/tickets.php?user_id=";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.ticketsfr, null);
listView = (ListView) view.findViewById(R.id.list3);
sendRequest();
return view;
}
private void sendRequest(){
String url = JSON_URL+Loginhandler.USER_ID;
StringRequest stringRequest = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error){
Toast.makeText(getActivity(),error.getMessage(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void showJSON(String json) {
Ticketshandler2 pj = new Ticketshandler2(json);
pj.parseJSON();
Ticketshandler cl = new Ticketshandler(getActivity(),
Ticketshandler2.event_name, Ticketshandler2.ticket_name,
Ticketshandler2.ticket_quantity, Ticketshandler2.ticket_description,
Ticketshandler2.ticket_channel, Ticketshandler2.ticket_start_date,
Ticketshandler2.ticket_end_date, Ticketshandler2.user_id);
listView.setAdapter(cl);
}
}
Ticketshandler.java:(Class)
public class Ticketshandler extends ArrayAdapter<String> {
TextView namme;
ProgressDialog loading;
private String[] event_name;
private String[] ticket_name;
private String[] ticket_quantity;
private String[] ticket_description;
private String[] ticket_channel;
private String[] ticket_start_date;
private String[] ticket_end_date;
private String[] user_id;
private Activity context;
public Ticketshandler(Activity context, String[] event_name, String[]
ticket_name,String[] ticket_quantity,String[] ticket_description,String[]
ticket_channel,String[] ticket_start_date,String[] ticket_end_date,String[]
user_id) {
super(context, R.layout.tickets_item, event_name);
this.context = context;
this.event_name = event_name;
this.ticket_name = ticket_name;
this.ticket_quantity = ticket_quantity;
this.ticket_description = ticket_description;
this.ticket_channel = ticket_channel;
this.ticket_start_date = ticket_start_date;
this.ticket_end_date = ticket_end_date;
this.user_id = user_id;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.tickets_item, null, true);
TextView event_topic_description = (TextView)
listViewItem.findViewById(R.id.titem);
String output = "" + event_name[position] + "\n" + ticket_name[position]
+ "\n" + ticket_quantity[position] + "\n" + ticket_description[position] +
"\n"
+ ticket_channel[position] + "\n" + ticket_start_date[position] + "\n" +
ticket_end_date[position];
// String output = "" +event_name[position];
event_topic_description.setText(output);
System.out.println(output);
return listViewItem;
}
}
Ticketshandler2.java:(Class)
public class Ticketshandler2 {
public static String[] event_name;
public static String[] ticket_name;
public static String[] ticket_quantity;
public static String[] ticket_description;
public static String[] ticket_channel;
public static String[] ticket_start_date;
public static String[] ticket_end_date;
public static String[] user_id;
public static final String JSON_ARRAY = "result";
public static final String EVENT_NAME = "event_name";
public static final String TICKET_NAME = "ticket_name";
public static final String TICKET_QUANTITY = "ticket_quantity";
public static final String TICKET_DESCRIPTION = "ticket_description";
public static final String TICKET_CHANNEL = "ticket_channel";
public static final String TICKET_START_DATE = "ticket_start_date";
public static final String TICKET_END_DATE = "ticket_end_date";
public static final String USER_ID = "user_id";
private JSONArray users = null;
private String json;
public Ticketshandler2(String json){
this.json = json;
}
protected void parseJSON(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
System.out.println(users);
event_name = new String[users.length()];
ticket_name = new String[users.length()];
ticket_quantity = new String[users.length()];
ticket_description = new String[users.length()];
ticket_channel = new String[users.length()];
ticket_start_date = new String[users.length()];
ticket_end_date = new String[users.length()];
user_id = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
event_name[i] = jo.getString(EVENT_NAME);
ticket_name[i] = jo.getString(TICKET_NAME);
ticket_quantity[i] = jo.getString(TICKET_QUANTITY);
ticket_description[i] = jo.getString(TICKET_DESCRIPTION);
ticket_channel[i] = jo.getString(TICKET_CHANNEL);
ticket_start_date[i] = jo.getString(TICKET_START_DATE);
ticket_end_date[i] = jo.getString(TICKET_END_DATE);
user_id[i] = jo.getString(USER_ID);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Log:
"12-09 12:00:17.750 31591-31591/com.example.dell.evento W/System.err:
org.json.JSONException: Value <br of type java.lang.String cannot be
converted to JSONObject"
I think my query has some issues, but it is working perfectly in wamp mysql separately..I dont understand what is the issue,, help...

Your response code might be not escape from htmlentities.
you need to first escape html string to proper character code.because java default not took any character code.

Related

Update same ListView with new data in CursorAdapter

I am really stuck and have no idea what to do. I have looked into startActivityForResult and Content providers and I have no clue how to implement any of them for this app.
I am not seeing how to get the data from the database and update the displayBottomList using same listview so I don't have to redirect the user to a new layout/activity. Not sure if I can even call a new query and set that to a different cursor and switch between them. I have seen swapCursor but how does that work when using the same adapter?
I have a ListView that I want to refresh with new data from a web service call when the user clicks on a row within the list. I am using a CursorAdapter. I can get the data correctly onClick of the row.
Where I am stuck, is how do I update that listView to repopulate with the new info from the database/response without sending me to another Activity. I want the user to stay on the same screen but just update the listView with the new data.
Not sure how to get the adapter to notify the adapter to update and populate a new ListView when the onClick is in the adapter, but the ListView is being created in the MainActivity.
The Adapter for BottomListView, the one I want to update when a row is clicked.
public class BottomListViewAdapter extends CursorAdapter {
private String mEmployeeNumber;
private EmployeeDBHandler dbHandler;
public BottomListViewAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.contact_cardview_layout, parent, false);
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
dbHandler = new EmployeeDBHandler(context);
ViewHolder holder;
holder = new ViewHolder();
holder.tvFirstName = (TextView) view.findViewById(R.id.personFirstName);
holder.tvLastName = (TextView) view.findViewById(R.id.personLastName);
holder.tvTitle = (TextView) view.findViewById(R.id.personTitle);
holder.mPeepPic = (ImageView) view.findViewById(R.id.person_photo);
holder.mDetailsButton = (ImageButton) view.findViewById(R.id.fullDetailButton);
holder.mCardView = (CardView) view.findViewById(R.id.home_screen_cardView);
String mFirstName = cursor.getString(cursor.getColumnIndexOrThrow("First_name"));
String mLastName = cursor.getString(cursor.getColumnIndexOrThrow("Last_name"));
String mTitle = cursor.getString(cursor.getColumnIndexOrThrow("Payroll_title"));
String mThumbnail = cursor.getString(cursor.getColumnIndexOrThrow("ThumbnailData"));
holder.tvFirstName.setText(mFirstName);
holder.tvLastName.setText(mLastName);
holder.tvTitle.setText(mTitle);
if (mThumbnail != null) {
byte[] imageAsBytes = Base64.decode(mThumbnail.getBytes(), Base64.DEFAULT);
Bitmap parsedImage = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
holder.mPeepPic.setImageBitmap(parsedImage);
} else {
holder.mPeepPic.setImageResource(R.drawable.img_place_holder_adapter);
}
final int position = cursor.getPosition();
holder.mDetailsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cursor.moveToPosition(position);
String mEmployeeNumber = cursor.getString(1);
String mEmail = cursor.getString(8);
String mFirstName = cursor.getString(2);
String mLastName = cursor.getString(3);
String mPhoneMobile = cursor.getString(4);
String mPhoneOffice = cursor.getString(5);
String mCostCenter = cursor.getString(10);
String mHasDirectReports = cursor.getString(7);
String mTitle = cursor.getString(6);
String mPic = cursor.getString(9);
Intent mIntent = new Intent(context, EmployeeFullInfo.class);
mIntent.putExtra("Employee_number", mEmployeeNumber);
mIntent.putExtra("Email", mEmail);
mIntent.putExtra("First_name", mFirstName);
mIntent.putExtra("Last_name", mLastName);
mIntent.putExtra("Phone_mobile", mPhoneMobile);
mIntent.putExtra("Phone_office", mPhoneOffice);
mIntent.putExtra("Cost_center_id", mCostCenter);
mIntent.putExtra("Has_direct_reports", mHasDirectReports);
mIntent.putExtra("Payroll_title", mTitle);
mIntent.putExtra("ThumbnailData", mPic);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
view.getContext().startActivity(mIntent);
}
});
holder.mCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cursor.moveToPosition(position);
mEmployeeNumber = cursor.getString(1);
Toast.makeText(context, mEmployeeNumber, Toast.LENGTH_SHORT).show();
callNewDirectReport();
notifyDataSetChanged();
}
});
}
public static class ViewHolder {
TextView tvFirstName;
TextView tvLastName;
TextView tvTitle;
ImageView mPeepPic;
ImageButton mDetailsButton;
CardView mCardView;
}
private void callNewDirectReport() {
String mDirectReportUrl = "mURL";
HttpUrl.Builder urlBuilder = HttpUrl.parse(mDirectReportUrl).newBuilder();
urlBuilder.addQueryParameter("manager_employee_number", mEmployeeNumber);
String url = urlBuilder.build().toString();
OkHttpClient client = getUnsafeOkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
final String responseData = response.body().string();
final InputStream stream = new ByteArrayInputStream(responseData.getBytes());
final XMLPullParserHandler parserHandler = new XMLPullParserHandler();
final ArrayList<Employee> employees = (ArrayList<Employee>) parserHandler.parse(stream);
for (Employee e : employees) {
dbHandler.addEmployee(e);
}
}
});
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
My MainActivity that is calling the adapter
public class MainActivity extends AppCompatActivity {
private ProgressBar mProgressBar;
private BottomListViewAdapter mBottomAdapter;
private View mDividerView;
EmployeeDBHandler dbHandler;
private int mStartingEmployeeID = mStartingID;
private String table = "employees";
private static final int LOADER_INTEGER = 1;
private Cursor mBottomCursor, mTopCursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mDividerView = findViewById(R.id.divider);
dbHandler = new EmployeeDBHandler(getApplicationContext());
mProgressBar.setVisibility(View.VISIBLE);
mDividerView.setVisibility(View.GONE);
getXMLData();
//GUI for seeing android SQLite Database in Chrome Dev Tools
Stetho.InitializerBuilder inBuilder = Stetho.newInitializerBuilder(this);
inBuilder.enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this));
Stetho.Initializer in = inBuilder.build();
Stetho.initialize(in);
}
public void getXMLData() {
OkHttpClient client = getUnsafeOkHttpClient();
Request request = new Request.Builder()
.url(getString(R.string.API_FULL_URL))
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
final String responseData = response.body().string();
final InputStream stream = new ByteArrayInputStream(responseData.getBytes());
final XMLPullParserHandler parserHandler = new XMLPullParserHandler();
final ArrayList<Employee> employees = (ArrayList<Employee>) parserHandler.parse(stream);
for (Employee e : employees) {
dbHandler.addEmployee(e);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressBar.setVisibility(View.GONE);
mDividerView.setVisibility(View.VISIBLE);
displayTopList();
displayBottomList();
}
});
}
});
}
public void displayTopList() {
SQLiteDatabase db = dbHandler.getWritableDatabase();
mTopCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " + "Employee_number" + "=" + mStartingEmployeeID, null);
ListView mTopListView = (ListView) findViewById(R.id.mTopList);
TopListCursorAdapter topAdapter = new TopListCursorAdapter(this, mTopCursor);
mTopListView.setAdapter(topAdapter);
}
public void displayBottomList() {
SQLiteDatabase db = dbHandler.getWritableDatabase();
mBottomCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " +
"Employee_number" + "!=" + mStartingEmployeeID + " AND " +
"Manager_employee_number" + "=" + mStartingEmployeeID + " ORDER BY " +
"Last_name" + " ASC", null);
ListView mBottomListView = (ListView) findViewById(R.id.mDirectReportList);
mBottomAdapter = new BottomListViewAdapter(this, mBottomCursor);
mBottomListView.setAdapter(mBottomAdapter);
mBottomAdapter.notifyDataSetChanged();
}
}
Right now your code in callNewDirectReport() makes an API request and stores the results in the database. This will not update the adapter to show the new items, instead you need to requery the database and get a newer Cursor. Below is an example of how you may do it:
public class BottomListViewAdapter extends CursorAdapter {
private String mEmployeeNumber;
private EmployeeDBHandler dbHandler;
private Activity activityRef;
public BottomListViewAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
// keep a reference to the activity
activityRef = (Activity) context;
}
//...
private void callNewDirectReport() {
//...
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
final String responseData = response.body().string();
final InputStream stream = new ByteArrayInputStream(responseData.getBytes());
final XMLPullParserHandler parserHandler = new XMLPullParserHandler();
final ArrayList<Employee> employees = (ArrayList<Employee>) parserHandler.parse(stream);
for (Employee e : employees) {
dbHandler.addEmployee(e);
}
// the new items are in the database so requery the database to get a new fresher Cursor:
SQLiteDatabase db = dbHandler.getWritableDatabase();
Cursor fresherCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " +
"Employee_number" + "!=" + mStartingEmployeeID + " AND " +
"Manager_employee_number" + "=" + mStartingEmployeeID + " ORDER BY " +
"Last_name" + " ASC", null);
//change the adapter's Cursor
activityRef.runOnUiThread(new Runnable() {
public void run() {
swapCursor(freshedCursor);
}
});
}
});
}
}
You can use startActivityForResult to receive a callback from an activity, here you have a tutorial explaining how to use it: https://developer.android.com/training/basics/intents/result.html
When you receive the callback in the onActivityResult, you can update your data and call notifyDatasetChanged.
You can't call code from an activity in another because activities are handled by android. Android could have killed the activity that you are trying to call and will just recreate it when necessary.

Json multiple array parsing is null

I am parsing json data and i have 2 array. I have successfully parse the 1st json array "item" ,now i have no idea how i can parse 2nd "img".
Here is my code :
{
"item": [
{
"description": "بافت عالی با قاب",
"price": "11000000000000",
"country": "ايران",
"address": "کوچه مهران یک پلاک7",
"region": "البرز",
"city": "کرج",
"mobile": null,
"cat": "حیوانات و مناظر طبیعی",
"img": [
"http://tajerfarsh.com/oc-content/themes/tgsh/images/slider/slider11.jpg",
"http://tajerfarsh.com/oc-content/themes/tgsh//images/categorys/109.jpg",
"http://tajerfarsh.com/oc-content/themes/tgsh//images/categorys/125.jpg"
]
}
]
}
and here is android side code :
public class ParseJSON1 {
public static String[] ids;
public static String[] descriptions;
public static String[] email;
public static String[] country;
public static String[] address;
public static String[] region;
public static String[] city;
public static String[] cat;
public static String[] image;
public static String[] mobiles;
public static final String JSON_ARRAY = "item";
public static final String KEY_ID = "id";
public static final String DESCCRIPTION = "description";
public static final String EMAIL = "emails";
public static final String COUNTRY = "country";
public static final String ADDRESS = "address";
public static final String REGION = "region";
public static final String CITY = "city";
public static final String CATEGORY = "cat";
public static final String IMAGE = "img";
public static final String MOBILE = "mobile";
private JSONArray users = null;
private String json;
public ParseJSON1(String json){
this.json = json;
}
protected void parseJSON1(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
ids = new String[users.length()];
descriptions = new String[users.length()];
country = new String[users.length()];
address = new String[users.length()];
region = new String[users.length()];
city = new String[users.length()];
cat = new String[users.length()];
email = new String[users.length()];
mobiles = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
ids[i] = jo.getString(KEY_ID);
descriptions[i] = jo.getString(DESCCRIPTION);
email[i] = jo.getString(EMAIL);
country[i] = jo.getString(COUNTRY);
address[i] = jo.getString(ADDRESS);
region[i] = jo.getString(REGION);
city[i] = jo.getString(CITY);
cat[i] = jo.getString(CATEGORY);
// image[i] = jo.getString(IMAGE);
mobiles[i] = jo.getString(MOBILE);
JSONArray img = jsonObject.getJSONArray("img");
image = new String[img.length()];
for (int j=0;j<img.length();j++){
image[i] = jo.getString(IMAGE);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
How to resolve it?
Parse it like this:
JSONArray img = jo.getJSONArray("img");
image = new String[img.length()];
for (int j=0;j<img.length();j++){
image[j] = img.getString(j);
}
Moreover, it's better to use a library like GSON for parsing.
Try implement the code below, this use List instead of arrays, it's less likely to have erros (like an Index of Bounds)
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
List<String> ids = new ArrayList<>();
List<String> descriptions = new ArrayList<>();
List<String> country = new ArrayList<>();
List<String> address = new ArrayList<>();
List<String> region = new ArrayList<>();
List<String> city = new ArrayList<>();
List<String> cat = new ArrayList<>();
List<String> email = new ArrayList<>();
List<String> mobiles = new ArrayList<>();
List<String[]> img = new ArrayList<>();
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
ids.add(jo.getString(KEY_ID));
// Do te rest of the "add"
JSONArray imgs = jo.getJSONArray(IMAGE)
image = new String[imgs.length()];
for (int j=0;j<imgs.length();j++){
image = jo.getString(j);
img .add(image);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}

How to implement a search for a ListView that uses ListAdapater, ArrayList and HashMap

I have a list view that I populate from a JSON array. First the values are extracted from the JSON array, then put into a HashMap. Then this HashMap is added to an ArrayList. From here, the necessary data is added to a ListAdapter.
I searched online for days now, to find a way to add a search function to this, but none of them uses this combination of ListAdapater, ArrayList and HashMap. I am a beginner so can someone help me do this please?
This is my code
public class ListNew extends Activity {
ListView list;
TextView eid;
TextView ename;
TextView edesc;
//Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "somelink";
//JSON Node Names
private static final String TAG_OS = "events";
private static final String TAG_EID = "eid";
private static final String TAG_ENAME = "ename";
private static final String TAG_ETYPE = "etype";
private static final String TAG_EDESC = "edesc";
private static final String TAG_ESDATE = "esdate";
private static final String TAG_EEDATE = "eedate";
private static final String TAG_ESTIME = "estime";
private static final String TAG_EETIME = "eetime";
private static final String TAG_LOCATION = "location";
private static final String TAG_CREATED_AT = "created_at";
private static final String TAG_EDITED_AT = "edited_at";
private static final String TAG_CREATEDBY = "createdby";
private static final String TAG_IMAGE = "image";
private static final String TAG_APPROVED = "approved";
EditText inputSearch;
ListAdapter adapter;
public static final String TABLE_EVENT = "event";
JSONArray events = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//from here
inputSearch = (EditText) findViewById(R.id.etSearch);
setContentView(R.layout.listnew);
oslist = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
eid = (TextView)findViewById(R.id.vers);
ename = (TextView)findViewById(R.id.name);
edesc = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(ListNew.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl2(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
events = json.getJSONArray(TAG_OS);
for(int i = 0; i < events.length(); i++){
JSONObject c = events.getJSONObject(i);
// Storing JSON item in a Variable
String eid = c.getString(TAG_EID);
String ename = c.getString(TAG_ENAME);
String etype = c.getString(TAG_ETYPE);
String edesc = c.getString(TAG_EDESC);
String esdate = c.getString(TAG_ESDATE);
String eedate = c.getString(TAG_EEDATE);
String estime = c.getString(TAG_ESTIME);
String eetime = c.getString(TAG_EETIME);
String location = c.getString(TAG_LOCATION);
String created_at = c.getString(TAG_CREATED_AT);
String edited_at = c.getString(TAG_EDITED_AT);
String createdby = c.getString(TAG_CREATEDBY);
String image = c.getString(TAG_IMAGE);
String approved = c.getString(TAG_APPROVED);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_EID, eid);
map.put(TAG_ENAME, ename);
map.put(TAG_ETYPE, etype);
map.put(TAG_EDESC, edesc);
map.put(TAG_ESDATE, esdate);
map.put(TAG_EEDATE, eedate);
map.put(TAG_ESTIME, estime);
map.put(TAG_EETIME, eetime);
map.put(TAG_LOCATION, location);
map.put(TAG_CREATED_AT, created_at);
map.put(TAG_EDITED_AT, edited_at);
map.put(TAG_CREATEDBY, createdby);
map.put(TAG_IMAGE, image);
map.put(TAG_APPROVED, approved);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
TextView emptyText = (TextView)findViewById(R.id.empty);
list.setEmptyView(emptyText);
//Log.d("TAG_is d first one", TAG_APPROVED + "," + approved);
adapter = new SimpleAdapter(ListNew.this, oslist,
R.layout.list_v,
new String[] { TAG_ENAME,TAG_CREATEDBY, TAG_CREATED_AT }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(ListNew.this, NewEvent.class);
i.putExtra("eid", oslist.get(+position).get("eid") );
i.putExtra("ename", oslist.get(+position).get("ename") );
i.putExtra("etype", oslist.get(+position).get("etype") );
i.putExtra("edesc", oslist.get(+position).get("edesc") );
i.putExtra("esdate", oslist.get(+position).get("esdate") );
i.putExtra("eedate", oslist.get(+position).get("eedate") );
i.putExtra("estime", oslist.get(+position).get("estime") );
i.putExtra("eetime", oslist.get(+position).get("eetime") );
i.putExtra("location", oslist.get(+position).get("location") );
i.putExtra("created_at", oslist.get(+position).get("created_at") );
i.putExtra("edited_at", oslist.get(+position).get("edited_at") );
i.putExtra("createdby", oslist.get(+position).get("createdby") );
i.putExtra("image", byteArray);
i.putExtra("approved", oslist.get(+position).get("approved") );
startActivity(i);
}
});
}//end if
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
As per you description I believe you have custom adapter implementation for your list view. In case of custom adapters yon need to create your own filters by implementing
http://developer.android.com/reference/android/widget/Filterable.html
or
http://developer.android.com/reference/android/widget/Filter.html
Below is the simple tutorial to take inspiration
http://www.survivingwithandroid.com/2012/10/android-listview-custom-filter-and.html
========== Example for simple search ===
You need to create an Edit text on top of list view
<EditText
android:id="#+id/editTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:maxLines="1" />
Then apply text change listener to this edit text
editTxt.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
and you are done.

While displaying data from sqlite database , for every onitemclick same data loads

I have written a program to insert json data into sqlite database in the form of a listview which is working perfectly , and with internet on , on every item click the details are also displaying correctly in the next activity.
But once when the data is loaded and i turn off the internet to load the data through sqlite database , the listview is displaying correctly but on every item click the details on the next activity are always the item which was last viewed.
cursor = listHelper.getAllData();
String[] columns = new String[] { DbListHelper.ARTWORK_IMAGE,
DbListHelper.WRAPPER_TYPE,
DbListHelper.ARTIST_NAME, DbListHelper.COLLECTION_NAME,
DbListHelper.TRACK_NAME,
DbListHelper.COLLECTION_PRICE, DbListHelper.TRACK_ID };
int[] to = new int[] { R.id.artworkImage, R.id.wrapperType,
R.id.artistName, R.id.collectionName,
R.id.trackName, R.id.collectionPrice, R.id.trackId };
dataAdapter = new CustomImageTextCursorAdapter(getBaseContext(),
R.layout.custom_row, cursor, columns, to);
lv.setAdapter(dataAdapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
Cursor cursor = (Cursor) parent.getItemAtPosition(position);
final int item_id =
cursor.getInt(cursor.getColumnIndex(DbListHelper.UID));
String item_content1 =
cursor.getString(cursor.getColumnIndex
(cursor.getColumnName(0)));
String item_content2 =
cursor.getString(cursor.getColumnIndex
(cursor.getColumnName(1)));
String item_content3 =
cursor.getString(cursor.getColumnIndex
(cursor.getColumnName(2)));
String item_content4 =
cursor.getString(cursor.getColumnIndex
(cursor.getColumnName(3)));
String item_content5 =
cursor.getString(cursor.getColumnIndex
(cursor.getColumnName(4)));
String item_content6 =
cursor.getString(cursor.getColumnIndex
(cursor.getColumnName(5)));
String item_content7 =
cursor.getString(cursor.getColumnIndex
(cursor.getColumnName(6)));
String item_content8 =
cursor.getString(cursor.getColumnIndex
(cursor.getColumnName(7)));
Intent intent = new Intent(MainActivity.this,
intent.putExtra("trackId", item_content8);
SingleTunesDetails.class);
startActivity(intent);
}
});
CustomImageTextCursorAdapter.java :
public class CustomImageTextCursorAdapter extends SimpleCursorAdapter {
private LayoutInflater mLayoutInflater;
private Context context;
private SqliteListHelper listHelper;
String extStorageDirectory;
File folder;
File file;
ImageLoader imageLoader;
int layout;
ConnectionDetector connectionDetector;
FileCache fileCache;
private class ViewHolder {
TextView wrapperType, artistName, collectionName, trackName, collectionPrice,trackId;
ImageView artworkImage;
ViewHolder(View v) {
wrapperType = (TextView) v.findViewById(R.id.wrapperType);
artistName = (TextView) v.findViewById(R.id.artistName);
collectionName = (TextView) v.findViewById(R.id.collectionName);
trackName = (TextView) v.findViewById(R.id.trackName);
collectionPrice = (TextView) v.findViewById(R.id.collectionPrice);
artworkImage = (ImageView) v.findViewById(R.id.artworkImage);
trackId = (TextView) v.findViewById(R.id.trackId);
listHelper = new SqliteListHelper(context);
listHelper.open(context);
}
}
public CustomImageTextCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
this.context = context;
this.layout = layout;
mLayoutInflater = LayoutInflater.from(context);
imageLoader = new ImageLoader(context);
connectionDetector = new ConnectionDetector(context);
fileCache = new FileCache(context);
}
public View newView(Context ctx, Cursor cursor, ViewGroup parent) {
View itemView = mLayoutInflater.inflate(R.layout.custom_row, parent,
false);
itemView.setTag(new ViewHolder(itemView));
return itemView;
}
#Override
public void bindView(View v, Context context, Cursor c) {
// you might want to cache these too
int index = c.getColumnIndex(DbListHelper.UID);
int cid = c.getInt(index);
int index0 = c.getColumnIndex(DbListHelper.ARTWORK_IMAGE);
String cid0 = c.getString(index0);
int index1 = c.getColumnIndex(DbListHelper.WRAPPER_TYPE);
String cid1 = c.getString(index1);
int index2 = c.getColumnIndex(DbListHelper.ARTIST_NAME);
String cid2 = c.getString(index2);
int index3 = c.getColumnIndex(DbListHelper.COLLECTION_NAME);
String cid3 = c.getString(index3);
int index4 = c.getColumnIndex(DbListHelper.TRACK_NAME);
String cid4 = c.getString(index4);
int index5 = c.getColumnIndex(DbListHelper.COLLECTION_PRICE);
String cid5 = c.getString(index5);
int index6 = c.getColumnIndex(DbListHelper.TRACK_ID);
String cid6 = c.getString(index6);
ViewHolder vh = (ViewHolder) v.getTag();
vh.wrapperType.setText(cid1);
vh.artistName.setText(cid2);
vh.collectionName.setText(cid3);
vh.trackName.setText(cid4);
vh.collectionPrice.setText(cid5);
vh.trackId.setText(cid6);
vh.trackId.setVisibility(View.GONE);
if (connectionDetector.isConnectingToInternet()) {
imageLoader.DisplayImage(cid0, vh.artworkImage);
} else {
File file = fileCache.getFile(cid0);
Log.i("TAG", "file_ path :" + file.getPath());
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
vh.artworkImage.setImageBitmap(myBitmap);
}
}
SingleItemDetails.java : In this class i am displaying json data from a url with parameter trackId passed from previous activity.
public class SingleItemDetails extends Activity {
// URL to get contacts JSON
private static String url = "";
// JSON Node names
static final String TAG_RESULT = "results";
static final String TAG_ARTWORK_IMAGE = "artworkUrl100";
static final String TAG_WRAPPER_TYPE = "wrapperType";
static final String TAG_ARTIST_NAME = "artistName";
static final String TAG_COLLECTION_NAME = "collectionName";
static final String TAG_TRACK_NAME = "trackName";
static final String TAG_COLLECTION_PRICE = "collectionPrice";
static final String TAG_TRACK_ID = "trackId";
// contacts JSONArray
JSONArray tracks = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> singleTrackDetails;
String passedData1;
TextView wrapperTypeText, artistNameText, collectionNameText, trackNameText,
collectionPriceText;
ImageView trackImage;
String artworkImage, wrapperType, artistName, collectionName, trackName,
collectionPrice, trackId;
private SqliteListHelper listHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_track);
singleTrackDetails = new ArrayList<HashMap<String, String>>();
wrapperTypeText = (TextView) findViewById(R.id.wrapperType1);
artistNameText = (TextView) findViewById(R.id.artistName1);
collectionNameText = (TextView) findViewById(R.id.collectionName1);
trackNameText = (TextView) findViewById(R.id.trackName1);
collectionPriceText = (TextView) findViewById(R.id.collectionPrice);
passedData1 = getIntent().getStringExtra("trackId");
listHelper = new SqliteListHelper(getBaseContext());
listHelper.open(getBaseContext());
url = "https://itunes.apple.com/lookup?id=" + passedData1;
// Calling async task to get json
new GetSingleTrackDetails().execute();
}
class GetSingleTrackDetails extends AsyncTask<Void, Void, Void> {
private JSONObject jsonObj;
#Override
protected Void doInBackground(Void... params) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
tracks = jsonObj.getJSONArray(TAG_RESULT);
// looping through All Products
for (int i = 0; i < tracks.length(); i++) {
JSONObject c = tracks.getJSONObject(i);
artworkImage = c.getString("artworkUrl100");
wrapperType = c.getString("wrapperType");
artistName = c.getString("artistName");
collectionName = c.getString("collectionName");
trackName = c.getString("trackName");
collectionPrice = c.getString("collectionPrice");
trackId = c.getString("trackId");
// tmp hashmap for single contact
HashMap<String, String> tunesMap = new HashMap<String,
String>();
// adding each child node to HashMap key => value
// contact.put(TAG_ID, firstname);
tunesMap.put(TAG_ARTWORK_IMAGE, artworkImage);
tunesMap.put(TAG_WRAPPER_TYPE, wrapperType);
tunesMap.put(TAG_ARTIST_NAME, artistName);
tunesMap.put(TAG_COLLECTION_NAME, collectionName);
tunesMap.put(TAG_TRACK_NAME, trackName);
tunesMap.put(TAG_COLLECTION_PRICE, collectionPrice);
tunesMap.put(TAG_TRACK_ID, trackId);
// adding contact to contact list
singleTrackDetails.add(tunesMap);
long id = listHelper.insertData2(artworkImage,
wrapperType, artistName, collectionName,
trackName, collectionPrice, trackId);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Cursor cursor = listHelper.getAllData2();
if (cursor.moveToFirst()) {
do{
String item_content1 = cursor.getString(cursor.getColumnIndex
(cursor.getColumnName(0)));
String item_content2 = cursor.getString(cursor.getColumnIndex
(cursor.getColumnName(1)));
String item_content3 = cursor.getString(cursor.getColumnIndex
(cursor.getColumnName(2)));
String item_content4 = cursor.getString(cursor.getColumnIndex
(cursor.getColumnName(3)));
String item_content5 = cursor.getString(cursor.getColumnIndex
(cursor.getColumnName(4)));
String item_content6 = cursor.getString(cursor.getColumnIndex
(cursor.getColumnName(5)));
String item_content7 = cursor.getString(cursor.getColumnIndex
(cursor.getColumnName(6)));
String item_content8 = cursor.getString(cursor.getColumnIndex
(cursor.getColumnName(7)));
wrapperTypeText.setText(item_content3);
artistNameText.setText(item_content4);
collectionNameText.setText(item_content5);
trackNameText.setText(item_content6);
collectionPriceText.setText(item_content7);
}while(cursor.moveToNext());
}
cursor.close();
}
}
Can anyone suggest me where i am going wrong ?
Thank You

Android different rows in listview

i have news application that download data from web and displays it in listview ,but how can i make that first row is different ,bigger height ,different layout and stuff ?
this is main activity source
public class Home extends Activity {
// All static variables
static final String URL = "http://dmb.site50.net/application.php?app_access_key=c4ca4238a0b923820dcc509a6f75849b";
// XML node keys
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";
public static final String TAG_NEWS = "news";
public static final String TAG_ID = "id";
public static final String TAG_TITLE = "title";
public static final String TAG_STORY = "story";
public static final String TAG_SH_STORY = "shorten";
public static final String TAG_DATETIME = "datetime";
public static final String TAG_AUTHOR = "author";
public static final String TAG_IMG = "img";
ListView list;
LazyAdapter adapter;
Button mBtnNaslovnica;
private ViewSwitcher viewSwitcher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
mBtnNaslovnica = (Button) findViewById(R.id.mBtnNaslovnica);
mBtnNaslovnica.setSelected(true);
TextView txtView=(TextView) findViewById(R.id.scroller);
txtView.setSelected(true);
ImageButton mBtnRefresh = (ImageButton) findViewById(R.id.btnRefresh);
mBtnRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new LoadingTask().execute(URL);
}
});
ArrayList<HashMap<String, String>> homeList = new ArrayList<HashMap<String, String>>();
JSONObject jsonobj;
try {
jsonobj = new JSONObject(getIntent().getStringExtra("json"));
JSONArray news = jsonobj.getJSONArray(TAG_NEWS);
for(int i = 0; i < news.length(); i++){
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String story = c.getString(TAG_STORY);
String shorten = c.getString(TAG_SH_STORY);
String author = c.getString(TAG_AUTHOR);
String datetime = c.getString(TAG_DATETIME);
String img = c.getString(TAG_IMG);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_STORY, story);
map.put(TAG_IMG, img);
map.put(TAG_DATETIME, datetime);
map.put(TAG_AUTHOR, author);
// adding HashList to ArrayList
homeList.add(map);}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, homeList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String cur_title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String cur_story = ((TextView) view.findViewById(R.id.einfo2)).getText().toString();
String cur_author = ((TextView) view.findViewById(R.id.einfo1)).getText().toString();
String cur_datetime = ((TextView) view.findViewById(R.id.einfo)).getText().toString();
ImageView cur_img = (ImageView) view.findViewById(R.id.list_image);
String cur_img_url = (String) cur_img.getTag();
Intent i = new Intent("com.example.androidhive.CURENTNEWS");
i.putExtra("CUR_TITLE", cur_title);
i.putExtra("CUR_STORY", cur_story);
i.putExtra("CUR_AUTHOR", cur_author);
i.putExtra("CUR_DATETIME", cur_datetime);
i.putExtra("CUR_IMG_URL", cur_img_url);
startActivity(i);
}
});
}
public void loadPage(){
}
public void startNewActivity(){
}
public class LoadingTask extends AsyncTask<String, Object, Object>{
XMLParser parser = new XMLParser();
JSONParser jParser = new JSONParser();
#Override
protected Object doInBackground(String... params) {
// TODO Auto-generated method stub
String URL = params[0];
JSONObject json = jParser.getJSONFromUrl(URL);
//String xml = parser.getXmlFromUrl(URL); // getting XML from URL
// getting DOM element
return json;
}
protected void onPostExecute(Object result){
Intent startApp = new Intent("com.example.androidhive.HOME");
startApp.putExtra("json", result.toString());
startActivity(startApp);
}
}
}
You need to modify your LazyAdapter code to return right layout for each row, depending on any criteria you want. ListView simply uses view given by adapter, so it is nothing special to have each row layouted differently. Please note that to make it work correctly you need to implement getItemViewType() and getViewTypeCount() as well.

Categories

Resources