i'm making a news app which in the news activity i have a tab slider with 2 tabs called , "new news" - "random or top news". which each tabs content are fragment.(i hope u get me!).
but the problem is im using a code to parse the this page content > http://aliak.xzn.ir/rap/get_all_products.php (i think u findout what site code im using)...
the problem is that if i want to show this in fragment(not activity) i have to write this code:
public class tab1 extends ListFragment {}
instead of this :
public class tab1 extends Fragment {}
and i the pager adapter i have problem which tells me the listfragment is not accepted! and if i dont use list fragment i have many errors!
THE CODES FOR APP :
my tab1 fragment ::
public class tab1 extends ListFragment {
//static final String url_all_products = "http://aliak.xzn.ir/rap/get_all_products.php";
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
final String TAG_SUCCESS = "success";
final String TAG_PRODUCTS = "products";
final String TAG_PID = "pid";
final String TAG_NAME = "name";
// JSON Node names
// products JSONArray
JSONArray products = null;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_1, container, false);
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("درحال دريافت اخبار،کمي صبر کنيد!");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest("http://aliak.xzn.ir/rap/get_all_products.php", "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getActivity().getApplicationContext(),
Main.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.list_item, new String[]{TAG_PID,
TAG_NAME},
new int[]{R.id.pid, R.id.name});
// updating listview
setListAdapter(adapter);
}
});
}
}
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
return v;
}
}
my adapter class :
/**
* Created by hp1 on 21-01-2015.
*/
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if (position == 0) // if the position is 0 we are returning the First tab
{
tab1 tab1 = new tab1();
return tab1;
} else // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
tab2 tab2 = new tab2();
return tab2;
}
}
/*
*/
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}
IF U NEEDED MORE CODES JUST TELL ME , ILL ANSWER IN 2 MIN TOPS!
check your imports and make sure your Fragment and ListFragment come from the same package, i.e. both android.support.v4.app.Fragment/ListFragment or both android.app.Fragment/ListFragment. Whichever one you use it has to be consistent with your actual fragment class implementations.
Related
Below is my code, I tried a lot but images are not not showing up though everything else shows up. and in logcat I got this following error.
E/BitmapFactory﹕ Unable to decode stream: java.io.FileNotFoundException: android.graphics.drawable.BitmapDrawable#29043558: open failed: ENOENT (No such file or directory)
I/System.out﹕ resolveUri failed on bad bitmap uri: android.graphics.drawable.BitmapDrawable#29043558
public class MainActivity extends ListActivity {
ImageView img2; Bitmap bitmapOrg;
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "xxxx://xxxxx.xx/xxxxx.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_TITLE = "title";
private static final String TAG_PRICE = "price";
private static final String TAG_Prix_Photo ="Photo";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
img2 = (ImageView) findViewById(R.id.Photo);
setContentView(R.layout.activity_main);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
ViewProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Entries: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String title = c.getString(TAG_TITLE);
String price = c.getString(TAG_PRICE);
String str1 = c.getString(TAG_Prix_Photo);
byte[] b = str1.getBytes();
byte[] ba2 = Base64.decode(b,Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(ba2, 0, ba2.length);
Drawable d = new BitmapDrawable(getResources(),bitmap);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_TITLE, title);
map.put(TAG_PRICE, price);
map.put(TAG_Prix_Photo, String.valueOf(d));
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
MainActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_TITLE, TAG_PRICE, TAG_Prix_Photo},
new int[] { R.id.pid, R.id.title, R.id.price,R.id.Photo});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
Try this;
Your image is in String so do this
String str1 = c.getString(TAG_Prix_Photo);
// byte[] b = str1.getBytes();
byte[] ba2 = Base64.decode(str1 ,Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(ba2, 0, ba2.length);
your php code must be become
base64_encode(base64_decode($row["TAG_Prix_Photo"]));
I've got a simple class. It loads data from my localhost and populates in a listview with android:id/list.
I've set a onclick listener to call my delete async task when I click an item.
My profileList.remove(position), works I can't seem to get the notifyDataSetChanged(); method to work and don't know where to place it?
Lastly, Im not sure but I don't think my class is referencing the position of the item I want to delete and matching it with my database? I keep getting "success=0 no profile" found in my LOG.
Any Ideas? I just want my count/listview to be refreshed and my item deleted.
Class:
public class ViewAllLocations extends ListActivity {
String id;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> profileList;
SimpleAdapter adapter;
// url to get all products list
private static String url_all_profile = "http://MYIP:8888/android_connect/get_all_location.php";
// url to delete product
private static final String url_delete_profile = "http://MYIP:8888/android_connect/delete_location.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_LOCATION = "Location";
private static final String TAG_ID = "id";
private static final String TAG_LATITUDE = "latitude";
private static final String TAG_LONGITUDE = "longitude";
// products JSONArray
JSONArray userprofile = null;
TextView locationCount;
int count = 0;
Button deleteLocation;
ListView lo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_locations);
// Hashmap for ListView
profileList = new ArrayList<HashMap<String, String>>();
deleteLocation = (Button) findViewById(R.id.deleteLocation);
locationCount = (TextView) findViewById(R.id.locationCount);
lo = (ListView) findViewById(android.R.id.list);
//setup adapter first //now no items, after getting items (LoadAllLocations) will update it
adapter = new SimpleAdapter(
ViewAllLocations.this, profileList,
R.layout.locationitem, new String[]{TAG_ID,
TAG_LATITUDE, TAG_LONGITUDE},
new int[]{R.id.id, R.id.latitude, R.id.longitude});
// updating listview
setListAdapter(adapter);
// Loading products in Background Thread
new LoadAllLocation().execute();
deleteLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
id = i.getStringExtra(TAG_ID);
// Get listview
ListView lo = getListView();
lo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
new DeleteLocation(position).execute();
Map<String, String> item = profileList.get(position);
String selectedItemId = item.get(TAG_ID);
new DeleteLocation(position).execute(selectedItemId);
}
});
}
/**
* **************************************************************
* Background Async Task to Delete Product
*/
class DeleteLocation extends AsyncTask<String, String, Integer> {
int deleteItemPosition;
public DeleteLocation(int position) {
// TODO Auto-generated constructor stub
this.deleteItemPosition = position;
}
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewAllLocations.this);
pDialog.setMessage("Deleting Location...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting product
*/
protected Integer doInBackground(String... args) {
String selectedId = args[0];
// Check for success tag
int success = 0; //0=failed 1=success
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", selectedId));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
url_delete_profile, "POST", params);
// check your log for json response
Log.d("Delete Product", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
//if (success == 1) {
// product successfully deleted
// notify previous activity by sending code 100
// Intent i = getIntent();
// send result code 100 to notify about product deletion
//setResult(100, i);
//you cant update UI on worker thread, it must be done on UI thread
// Toast.makeText(getApplicationContext(), "Location Deleted",
// Toast.LENGTH_SHORT).show();
//finish();
// }
} catch (JSONException e) {
e.printStackTrace();
}
return success;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(Integer result) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (result == 1) {
//success
//delete from list and update listview
profileList.remove(deleteItemPosition);
adapter.notifyDataSetChanged();
} else {
//failed
}
}
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllLocation extends AsyncTask<String, String, Integer> {
int success;
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewAllLocations.this);
pDialog.setMessage("Loading Locations. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected Integer doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(url_all_profile, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Profiles: ", json.toString());
try {
// Checking for SUCCESS TAG
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
userprofile = json.getJSONArray(TAG_LOCATION);
// looping through All Products
for (int i = 0; i < userprofile.length(); i++) {
JSONObject c = userprofile.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String latitude = c.getString(TAG_LATITUDE);
String longitude = c.getString(TAG_LONGITUDE);
// 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_LATITUDE, latitude);
map.put(TAG_LONGITUDE, longitude);
// adding HashList to ArrayList
profileList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
//Intent i = new Intent(getApplicationContext(),
// UserLocation.class);
// Closing all previous activities
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return success;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(Integer result) {
// dismiss the dialog after getting all products
pDialog.dismiss();
locationCount.setText("" + profileList.size());
if (result == 1) {
//success
//update adapter items
adapter.notifyDataSetChanged();
} else {
//failed
//launch activity here
}
}
}
PHP:
<?php
/*
* Following code will delete a profile from table
* A product is identified by profile id (id)
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['id'])) {
$id = $_POST['id'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql update row with matched pid
$result = mysql_query("DELETE FROM Location WHERE id = $id");
// check if row deleted or not
if (mysql_affected_rows() > 0) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Profile successfully deleted";
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No Profile found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Can i call a single activity in listview, i have searching any code but i never understand how to implement it because i use JSON parsing in my code. can someone tell me how to do it with my code.
Here my MainActivity.java
public class MainActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> DaftarRS;
private static String url_daftar_rs = "http://192.168.43.226/jualan/barang_tes/list.php";
// JSON Node names
public static final String TAG_SUCCESS = "success";
public static final String TAG_DAFTAR_RS = "daftar_rs";
public static final String TAG_ID_RS = "id_rs";
public static final String TAG_NAMA_RS = "nama_rs";
public static final String TAG_LINK_IMAGE_RS = "link_image_rs";
public static final String TAG_ALAMAT_RS = "alamat_rs";
public static final String TAG_TELEPON_RS = "telepon_rs";
public static final String TAG_HARGA_RS = "harga_rs";
Button ButttonInputRumahSakit;
// daftar_rs JSONArray
JSONArray daftar_rs = null;
ListView list;
ListAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_load_barang);
// Hashmap for ListView
DaftarRS = new ArrayList<HashMap<String, String>>();
// Loading in Background Thread
new LoadDaftarRumahSakitActivity().execute();
// Get listview
list = (ListView) findViewById(R.id.list);
// Launching new screen on Selecting Single ListItem
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = DaftarRS.get(position);
Intent in = new Intent(MainActivity.this, SingleMenuItemActivity.class);
in.putExtra(TAG_ID_RS, map.get(TAG_ID_RS));
in.putExtra(TAG_NAMA_RS, map.get(TAG_NAMA_RS));
in.putExtra(TAG_LINK_IMAGE_RS, map.get(TAG_LINK_IMAGE_RS));
in.putExtra(TAG_ALAMAT_RS, map.get(TAG_ALAMAT_RS));
in.putExtra(TAG_TELEPON_RS, map.get(TAG_TELEPON_RS));
in.putExtra(TAG_HARGA_RS, map.get(TAG_HARGA_RS));
startActivity(in);
}
});
}
/**
*Updating parsed JSON data into ListView
**/
public void SetListViewAdapter(ArrayList<HashMap<String, String>> daftar) {
adapter = new ListAdapter(this, daftar);
list.setAdapter(adapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
//if result code 100 is received
//means user edited/deleted record
//reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
*Background Async Task to Load all record data by making HTTP Request
**/
class LoadDaftarRumahSakitActivity extends AsyncTask<String, String, String> {
/**
*Before starting background thread Show Progress Dialog
**/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Mohon tunggu...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
*getting All record data from url
**/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_daftar_rs, "GET", params);
// Check your log cat for JSON reponse
Log.d("Daftar Rumah Sakit: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
//Ada record Data (SUCCESS = 1)
//Getting Array of daftar_rs
daftar_rs = json.getJSONArray(TAG_DAFTAR_RS);
// looping through All daftar_rs
for (int i = 0; i < daftar_rs.length(); i++) {
JSONObject c = daftar_rs.getJSONObject(i);
//Storing each json item in variable
String id_rs = c.getString(TAG_ID_RS);
String nama_rs = c.getString(TAG_NAMA_RS);
String link_image_rs = c.getString(TAG_LINK_IMAGE_RS);
String alamat_rs = c.getString(TAG_ALAMAT_RS);
String telepon_rs = c.getString(TAG_TELEPON_RS);
String harga_rs = c.getString(TAG_HARGA_RS);
//creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to HashMap key => value
map.put(TAG_ID_RS, id_rs);
map.put(TAG_NAMA_RS, nama_rs);
map.put(TAG_LINK_IMAGE_RS, link_image_rs);
map.put(TAG_ALAMAT_RS, alamat_rs);
map.put(TAG_TELEPON_RS, telepon_rs);
map.put(TAG_HARGA_RS, harga_rs);
//adding HashList to ArrayList
DaftarRS.add(map);
}
} else {
//Tidak Ada Record Data (SUCCESS = 0)
//Akan menutup aplikasi
finish();
}
} catch (JSONException e) { e.printStackTrace();
}
return null;
}
/**
*After completing background task Dismiss the progress dialog
***/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all record rumah sakit
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// updating listview
SetListViewAdapter(DaftarRS);
}
});
}
}
}
Here my SingleMenuItemActivity.java
public class SingleMenuItemActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list);
Intent i = getIntent();
//now your item data are in i
String TAG_ID_RS = i.getStringExtra("TAG_ID_RS");
String TAG_NAMA_RS = i.getStringExtra("TAG_NAMA_RS");
String TAG_LINK_IMAGE_RS = i.getStringExtra("TAG_LINK_IMAGE_RS");
String TAG_ALAMAT_RS = i.getStringExtra("TAG_ALAMAT_RS");
String TAG_TELEPON_RS = i.getStringExtra("TAG_TELEPON_RS");
String TAG_HARGA_RS = i.getStringExtra("TAG_HARGA_RS");
TextView namaView = (TextView) findViewById(R.id.nama_rs);
ImageView link_img = (ImageView) findViewById(R.id.image_rs);
TextView alamat = (TextView) findViewById(R.id.alamat_rs);
TextView telepon = (TextView) findViewById(R.id.telepon_rs);
TextView harga = (TextView) findViewById(R.id.harga_rs);
namaView.setText(TAG_NAMA_RS);
//link_img.setImageBitmap(TAG_LINK_IMAGE_RS);
alamat.setText(TAG_ALAMAT_RS);
telepon.setText(TAG_TELEPON_RS);
harga.setText(TAG_HARGA_RS);
}
}
In your main activity's onCreate method, after your last line add:
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
HashMap<String,String> item = (HashMap<String,String>) adapter.getItem(position);
Intent intent = new Intent(this, YourSecondActivity.class);
intent.putExtra("TAG_ID_RS", item.get("TAG_ID_RS"));
intent.putExtra("TAG_NAMA_RS", item.get("TAG_NAMA_RS"));
......
startActivity(intent);
}
});
In the YourSecondActivity.java there goes something like:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yoursecondactivity);
Intent i = getIntent();
//now your item data are in i
String TAG_ID_RS = i.getString("TAG_ID_RS");
String TAG_NAMA_RS = i.getString("TAG_NAMA_RS");
....
TextView namaView = (TextView)findViewById(R.id.yourNameView);
namaView.setText(TAG_NAMA_RS);
....
}
For your intent receiving activity you need to define an intent filter in the manifest file:
<activity android:name="SingleMenuItemActivity">
<intent-filter>
<action android:name="yourpackage.intent.action.showsinglemenuitem"/>
</intent-filter>
</activity>
Use the "yourpackage.intent.action.showsinglemenuitem" action name when constructing the INTENT to be p
I think I found out your problem finally:
In your MainActivity you define your field names as for example:
public static final String TAG_NAMA_RS = "nama_rs";
and you fill them with that name into the Intent,
but in your SingleMenuItemActivity you are trying to access them with different name:
String TAG_NAMA_RS = i.getStringExtra("TAG_NAMA_RS");
you need to do
String TAG_NAMA_RS = i.getStringExtra("nama_rs");
I set up this listvide like this from the data elements I received from a json request. Now what I'm not to sure about is how would I delete an listitem from this listview on a long click.
This is the background activity that populates the listview
class readNotifications extends AsyncTask<String, String, String>{
;
#Override
protected String doInBackground(String... params) {
// TODO Auto-generatNameValuePairb
List<NameValuePair>param=new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("id",SaveSharedPreference.getUserId(Notifications.this))); //SaveSharedPreference.getUserId(Notifications.this)
JSONObject json=jsonParser.makeHttpRequest(url_notifications, "POST", param);
Log.d("My Notifications", json.toString());
try {
JSONArray array = json.getJSONArray("notifications");
Log.d("Notifications length",Integer.toString(array.length()));
//if(array.length()==0)
//Log.d("Messages?","No Messages");
if(array.length()>0){
for (int i = 0; i < array.length(); i++) {
// Log.i("name", array.getJSONObject(i).getString("name"));
JSONObject c = array.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("notification_id");
String message = c.getString("message");
//Log.i("picture_url", picture);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("notification_id", id);
map.put("message", message);
// adding HashList to ArrayList
notifications.add(map);
}
}else{
runOnUiThread(new Runnable() {
public void run() {
TextView tx=(TextView)findViewById(R.id.nonotifications);
tx.setVisibility(0);
}
});
//Log.d("Notifications length",Integer.toString(array.length()));
}
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
Notifications.this, notifications,
R.layout.notifications, new String[] { "notification_id","message"},
new int[] { R.id.pid, R.id.notification});
// updating listview
setListAdapter(adapter);
}
});
}
}
class deleteNotification extends AsyncTask<String, String, String>{
String theirId=((TextView) findViewById(R.id.pid)).getText().toString();
#Override
protected String doInBackground(String... params) {
// TODO Auto-generatNameValuePairb
List<NameValuePair>param=new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("id",SaveSharedPreference.getUserId(Notifications.this))); //SaveSharedPreference.getUserId(Notifications.this)
param.add(new BasicNameValuePair("nid",notiId));
JSONObject json=jsonParser.makeHttpRequest(url_delete_notification, "POST", param);
Log.d("Their Id", theirId );
Log.d("My Notifications", json.toString());
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
//new readNotifications().execute();
}
});
}
}
This is the start of the longclicklistener I did.
ListView lv= getListView();
registerForContextMenu(lv);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id)
yeah so I don't know how I would delete any item from the listview.
You remove the item from the list adapter and call notifyDataSetChanged().
The plain ListAdapter doesn't have a remove method, and I don't know what SimpleAdapter extends, but ArrayAdapter has a remove method and you could add your own to a BaseAdapter.
Btw, if you want a simpler way to create a ListAdapter, this may help (make a class that extends SilkAdapter instead of ArrayAdapter or whatever you're using): https://github.com/afollestad/Silk/blob/master/src/com/afollestad/silk/adapters/SilkAdapter.java
Now what I'm not to sure about is how would I delete an listitem from
this listview on a long click.
You just have to remove the item from your dataset and call notifyDataSetChanged on the ListViews adapter.
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id){
notifications.remove(pos);
adapter.notifyDataSetChanged();
}
Hi i have to developed listview with load more button using xml parsing in android application.
Here i have faced some problem.
my xml feed is empty means how can hide the load more button on last page.
i have used below code here.
public class CustomizedListView extends Activity {
// All static variables
private String URL = "http://dev.mmm.com/xctesting/xcart444pro/retrieve.php?page=1";
// XML node keys
static final String KEY_SONG = "Order";
static final String KEY_TITLE = "orderid";
static final String KEY_DATE = "date";
static final String KEY_ARTIST = "payment_method";
int current_page = 1;
ListView lv;
LazyAdapter adapter;
ProgressDialog pDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView) findViewById(R.id.list);
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_SONG);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
songsList.add(map);
}
Button btnLoadMore = new Button(this);
btnLoadMore.setText("Load More");
btnLoadMore.setBackgroundResource(R.drawable.lgnbttn);
// Adding Load More button to lisview at bottom
lv.addFooterView(btnLoadMore);
// Getting adapter
adapter = new LazyAdapter(this, songsList);
lv.setAdapter(adapter);
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Starting a new async task
new loadMoreListView().execute();
}
});
}
private class loadMoreListView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(
CustomizedListView.this);
pDialog.setMessage("Please wait..");
//pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.my_progress_indeterminate));
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
pDialog.setContentView(R.layout.custom_dialog);
}
protected Void doInBackground(Void... unused) {
current_page += 1;
// Next page request
URL = "http://dev.mmm.com/xctesting/xcart444pro/retrieve.php?page=" + current_page;
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_SONG);
NodeList nl = doc.getElementsByTagName(KEY_SONG);
if (nl.getLength() == 0)
{
btnLoadMore.setVisibility(View.GONE);
pDialog.dismiss();
}
else
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
songsList.add(map);
}
// get listview current position - used to maintain scroll position
int currentPosition = lv.getFirstVisiblePosition();
// Appending new data to menuItems ArrayList
adapter = new LazyAdapter(
CustomizedListView.this,
songsList);
lv.setAdapter(adapter);
lv.setSelectionFromTop(currentPosition + 1, 0);
}
});
return (null);
}
protected void onPostExecute(Void unused) {
// closing progress dialog
pDialog.dismiss();
}
}
}
EDIT:
Here i have to run the app means the listview is displayed on perpage 4 items.my last page having 1 item.please refer this screenshot:lastpage
In last page i have to click the load more button means have to go next activity and successfully hide the button on empty page..please refer this screenshot:empty page-so hide the button
i have to check the condition for empty page:
if (nl.getLength() == 0)
{
btnLoadMore.setVisibility(View.GONE);
pDialog.dismiss();
}
How can i write the conditon fot last page?????pleas ehelp me
Here i wish to need the o/p is hide the button on last page.
Please help me.how can i check the condition.give me some code programmatically.
First off, why are you using runOnUiThread inside an AsyncTaks? This should not be necessary. The code that has to run in the background, in the doInBackground method is enough.
Furthermore, you could use the third parameter type of the AsyncTask to return a result from te doInBackground to the onPostExecute. Then depending on the result, you can change the visibility of the button there.
To do this, the reference to the Button (btnLoadMore in your case) should be a instance variable, so it should be defined in the class, not in the onCreate method. Otherwise it will not be accessible from outside this method.
I asume the nodelist will be empty when the feed is empty? Then it will look something like this:
public class CustomizedListView extends Activity {
private Button btnLoadMore;
public void onCreate(){
btnLoadMore = new Button(this);
<do stuff>
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Starting a new async task
new LoadMoreListView().execute();
}
});
new LoadMoreListView().execute();// execute the AsyncTask once in the onCreate, so you don't have to duplicate the code here to load the listview.
}
private class LoadMoreListView extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
< Show dialog>;
}
#Override
protected Void doInBackground(Void... unused) {
Boolean listIsEmpty;
< Page request>;
< Retrieve element list>;
< If element list size == 0, listIsEmpty = true; return listIsEmpty>;
< Process elements, fill list etc.>;
< End of doInBackground, listIsEmpty = false; return listIsEmpty>;
}
#Override
protected void onPostExecute(Boolean listIsEmpty) {
< If listIsEmpty == true -> btnLoadMore.setVisibility(View.GONE);>
< Close dialog>
}
}
}
}
I achieved load more using this way I dont use footer view for it
public boolean mHasLoadMore = false;
class MyAdapter extends ArrayAdapter implements OnItemClickListener{
public MyAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
public int getTotal(){
return super.getCount();
}
#Override
public int getCount() {
if(super.getCount()>0)
return super.getCount()+1;
else
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if( getTotal() == (position+1) && mHasLoadMore ){
TextView loadMoreView = new TextView(getContext());
loadMoreView.setText("Load More");
return loadMoreView;
}
else {
View theView = new View(getContext());
// inflate & add what you need for item view here you can modify it to reuse convertView also
return theView;
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
if( getTotal() == (position+1) && mHasLoadMore ){
// load more button clicked do handling for load more launch async
//task to do load more after that if found 0 result change mHasLoadMore to false
//& call notifydatadetchanged
}
else
{
// handle item click here
}
}
}
Use such adapter for your listview & set value of mHasLoadMore first time while loading data & call notifydatasetchanged