How to intent KEY_URL data the WV activity ?
I hope I could tell I. Thank you in advance for your help.
This is my intent button
button = (Button) findViewById(R.id.haftalikizle);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), VW.class);
i.putExtra("link",(KEY_URL).toString());
startActivity(i);
}});
This my full code, but not work. ideas, thoughts, or you can edit your.
public class haftalik extends ListActivity {
static final String URL = "https://dl.dropboxusercontent.com/s/qd33n0zxcmrnsf2/haftalik.xml";
static final String KEY_ITEM = "item";
static final String KEY_ID = "id";
static final String KEY_BILGI = "bilgi";
static final String KEY_URL = "url";
static final String KEY_THUMB_URL = "thumb_url";
public WebView tarayici;
private ProgressDialog pDialog;
ConnectivityManager connectivity = null;
ListView lv;
haftalik2 adapter;
ArrayList<HashMap<String, String>> catalogList;
Button button;
//#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.haftalik_main);
if(isConn())
{
catalogList= new ArrayList<HashMap<String, String>>();
new LoadCatalog().execute();
}
else
{
Intent i = new Intent(getApplicationContext(), dene.class);
startActivity(i);
this.finish();
}
}
class LoadCatalog extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(haftalik.this);
// pDialog.setMessage("");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
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_ITEM);
// 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_BILGI, parser.getValue(e, KEY_BILGI));
map.put(KEY_URL, parser.getValue(e, KEY_URL));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
catalogList.add(map);
}
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() {
lv=getListView();
adapter=new haftalik2(haftalik.this, catalogList);
lv.setAdapter(adapter);
pDialog.dismiss();
}
});
button = (Button) findViewById(R.id.haftalikizle);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), VW.class);
i.putExtra("link",(KEY_URL).toString());
startActivity(i);
}});
}
}
public boolean isConn(){
connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivity.getActiveNetworkInfo()!=null){
if(connectivity.getActiveNetworkInfo().isConnected())
return true;
}
return false;
}
}
and my adapter class
public class haftalik2 extends BaseAdapter {
String url=null;
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public haftalik2(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.haftalik, null);
TextView bilgi = (TextView)vi.findViewById(R.id.bilgi);
//TextView url = (TextView)vi.findViewById(R.id.url);
ImageView thumb_image=(ImageView)vi.findViewById(R.id.poster);
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
bilgi.setText(song.get(haftalik.KEY_BILGI));
//url.setText(song.get(haftalik.KEY_URL));
imageLoader.DisplayImage(song.get(haftalik.KEY_THUMB_URL), thumb_image);
return vi;
}
}
Related
I have a database with table image, i have atribut id_image(int), image_name(string)
This is the web services that will be used to get the image_name URL=http://lomapod.azurewebsites.net/readBarang.php?id_penjual=1
This is how will i call the ImageURL
ImageUrl= http://lomapod.esy.es/assets/(image_name).jpg
gridItem.java
public class gridItem {
String imageUrl;
String barang;
public gridItem(String barang, String imageUrl) {
super();
this.imageUrl = imageUrl;
this.barang = barang;
}
public String getImageUrl() {
return imageUrl;
}
public String getBarang() {
return barang;
}
}
CustomGridViewAdapter.Java
public class CustomGridViewAdapter extends ArrayAdapter<gridItem> {
Context context;
int layoutResourceId;
ArrayList<gridItem> data = new ArrayList<>();
public CustomGridViewAdapter(Context context, int layoutResourceId,
ArrayList<gridItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RecordHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RecordHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.tvItem);
holder.imageItem = (ImageView) row.findViewById(R.id.imageView);
row.setTag(holder);
} else {
holder = (RecordHolder) row.getTag();
}
gridItem item = data.get(position);
holder.txtTitle.setText(item.getBarang());
Picasso.with(context).
load(item.getImageUrl()).
into(holder.imageItem);
return row;
}
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
}
}
MainActivity.Java
public class MainActivity extends ActionBarActivity {
JSONParser jParser= new JSONParser();
ArrayList<HashMap<String, String>> nameList;
JSONArray names=null;
GridView data;
private static final String URL_TEST_BARANG= "http://lomapod.azurewebsites.net/readBarang.php?id_penjual=1";
private static final String TAG_PESAN = "message";
private static final String TAG_HASIL = "result";
private static final String TAG_BARANG = "nama_barang";
private static final String TAG_IMAGE= "image_name";
ImageView imageview;
CustomGridViewAdapter mGridAdapter;
ArrayList<gridItem> mGridData;
public MainActivity()
{}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data=(GridView) findViewById(R.id.lvSeller);
nameList= new ArrayList<HashMap<String, String>>();
imageview =(ImageView) findViewById(R.id.imageView);
mGridData=new ArrayList<>();
mGridAdapter=new CustomGridViewAdapter(this,R.layout.grid_item,mGridData);
data.setAdapter(mGridAdapter);
new AmbilDataJson().execute();
}
public class AmbilDataJson extends AsyncTask<String,String,String> {
int sukses=0;
public AmbilDataJson() {}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
try
{
JSONObject json = jParser.makeHttpRequest(URL_TEST_BARANG, "GET", params);
if(json != null)
{
sukses = json.getInt(TAG_PESAN);
if(sukses == 0)
{
nameList = new ArrayList<HashMap<String,String>>();
Log.d("Semua Nama: ", json.toString());
names = json.getJSONArray(TAG_HASIL);
for(int i = 0; i < names.length();i++)
{
JSONObject c = names.getJSONObject(i);
String barang = c.getString(TAG_BARANG);
String image = "lomapod.esy.es/assets/"+c.getString(TAG_IMAGE);
HashMap<String,String> map = new HashMap<String,String>();
map.put(TAG_BARANG,barang);
map.put(TAG_IMAGE,image);
nameList.add(map);
}
}
}
}catch(JSONException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
if(sukses == 0)
{
CustomGridViewAdapter adapter = new CustomGridViewAdapter(
MainActivity.this,R.layout.grid_item,mGridData);
mGridAdapter.setGridData(mGridData);
}
else
{
Toast.makeText(MainActivity.this,"Failed",Toast.LENGTH_LONG);
}
}
}
}
I want to display the image to gridview in android studio, but i don't what should i do in MainActivity.
Can anyone tell me how? Thanks in advanced
Firstly, you need to fill your List, and pass it to the adapter. After that, you need to set your adapter to GridView.
here I have added my invitation(event) fragment code here I want to change the color of the button when I clicked particular button for particular event in listview
public class InvitationFragment extends Fragment {
LayoutInflater inflater;
ViewGroup container;
Bundle savedInstanceState;
private List<String> eventName = new ArrayList<>();
private List<Long> eventId = new ArrayList<>();
private List<String> eventPlace = new ArrayList<>();
private List<EventMO> eventMOs = new ArrayList<>();
private List<Long> eventUserId = new ArrayList<>();
private Context context;
private UserOccasions userOccasions;
private UserDelegate userDelegate = new UserDelegate();
private EventDelegates eventDelegates = new EventDelegates();
private Gson gson = new Gson();
private ProgressDialog prgDialog;
private UserMO userMO;
private CheckBox invitationCheckBox;
private ListView occasionView;
private DatabaseHelper dbHelper;
private View view;
private SharedPreferences sharedpreferences;
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("onOptionsItemSelected", "yes");
switch (item.getItemId()) {
case R.id.menu_cancel_event:
displayInvitationList();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void displayInvitationList() {
int itemCount = occasionView.getCheckedItemCount();
for (int i = 1; i <= itemCount; i++) {
if (userOccasions.getCheckedInvitationCount() != null) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
// eventUserId = userOccasions.getCheckedInvitationCount();
// db.delete("user_relation", "EVENT_USER_ID" + " = ?", new String[]{Long.toString(eventUserId)});
db.close();
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
this.inflater = inflater;
this.container = container;
this.savedInstanceState = savedInstanceState;
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
final View view = inflater.inflate(R.layout.invitation_tab, container, false);
context = getActivity().getApplicationContext();
prgDialog = new ProgressDialog(getActivity());
eventId.clear();
eventName.clear();
eventPlace.clear();
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
prgDialog.show();
DatabaseHelper dbHelper = new DatabaseHelper(context);
userMO = dbHelper.getRingeeUserData(1);
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return eventDelegates.getAllEventForUser(userMO, context);
}
#Override
protected void onPostExecute(String eventLists) {
if (eventLists != "null") {
eventMOs = gson.fromJson(eventLists, new TypeToken<List<EventMO>>() {
}.getType());
Toast.makeText(context, "total items of eventMo" + eventMOs.size(), Toast.LENGTH_LONG).show();
for (EventMO eventMO : eventMOs) {
eventName.add(eventMO.getText());
eventId.add(eventMO.getEventId());
eventPlace.add(eventMO.getPlace());
}
DatabaseHelper dbHelper = new DatabaseHelper(context);
//long totalInsertion = dbHelper.insertUserRelationTable(userMOs);
prgDialog.dismiss();
//Toast.makeText(context, "total userMos size " + userMOs.size() + "total db insertion size " + totalInsertion, Toast.LENGTH_LONG).show();
occasionView = (ListView) view.findViewById(R.id.invitation_list_view);
userOccasions = new UserOccasions();
occasionView.setAdapter(userOccasions);
occasionView.setItemsCanFocus(false);
occasionView.setTextFilterEnabled(true);
occasionView.setOnItemClickListener(occasionView.getOnItemClickListener());
}
}
}.execute(null, null, null);
return view;
}
private class UserOccasions extends BaseAdapter {
LayoutInflater mInflater;
TextView eventNameTxtV, eventPlaceTxtV;
private ArrayList<EventMO> checkedInvitationItems;
private Object invitationTag;
UserOccasions() {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.checkedInvitationItems = new ArrayList<EventMO>();
}
#Override
public int getCount() {
return eventMOs.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return 0;
}
// show list values name and mobile number in contact page
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (null == convertView) {
convertView = mInflater.inflate(R.layout.invitation, null);
}
eventNameTxtV = (TextView) convertView.findViewById(R.id.invitationTitle);
eventPlaceTxtV = (TextView) convertView.findViewById(R.id.invitationPlace);
eventNameTxtV.setText(eventMOs.get(position).getText());
eventPlaceTxtV.setText(eventMOs.get(position).getPlace());
// intializing variables
final EventMO eventMO = eventMOs.get(position);
convertView.setTag(position);
View v = convertView.findViewById(R.id.invitation_single);
final LinearLayout eventLayout = (LinearLayout) convertView.findViewById(R.id.invitation_single);
invitationCheckBox = (CheckBox) convertView.findViewById(R.id.invitationCheckBox);
Button yesBtn = (Button) convertView.findViewById(R.id.yesButton);
Button noBtn = (Button) convertView.findViewById(R.id.noButton);
Button maybeBtn = (Button) convertView.findViewById(R.id.buttonMayBe);
final LinearLayout responseLayout = (LinearLayout) convertView.findViewById(R.id.hidden);
invitationCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
checkedInvitationItems.add((EventMO) eventMO);
} else {
checkedInvitationItems.remove((EventMO) eventMO);
}
}
});
//Based on the user click, response will be stored
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
responseLayout.setVisibility(View.GONE);
//If user clicks yes button in invitation response layout,response would be stored as 1 for event user
final int response = 1;
final long eventId = eventMOs.get(position).getEventId();
userMO.setIsAttending(response);
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return userDelegate.updateEventUserRelationShipMapping(userMO, eventId);
}
}.execute(null, null, null);
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
responseLayout.setVisibility(View.GONE);
//If user clicks no button in invitation response layout,response would be stored as 0 for event user
final int response = 0;
final long eventId = eventMOs.get(position).getEventId();
userMO.setIsAttending(response);
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return userDelegate.updateEventUserRelationShipMapping(userMO, eventId);
}
}.execute(null, null, null);
}
});
maybeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
responseLayout.setVisibility(View.GONE);
//If user clicks maybe button in invitation response layout,response would be stored as for event user
final int response = 2;
userMO.setIsAttending(response);
final long eventId = eventMOs.get(position).getEventId();
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return userDelegate.updateEventUserRelationShipMapping(userMO, eventId);
}
}.execute(null, null, null);
}
});
eventLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.invitation_single:
responseLayout.setVisibility(View.VISIBLE);
break;
}
}
});
return convertView;
}
public ArrayList<EventMO> getCheckedInvitationCount() {
return this.checkedInvitationItems;
}
}
}
here I have tried the following code for change the colour of the button when the button clicked but it will not hold the colour when we go back and return back to the button and it will work for all events
yesBtn.setbackgroundColor(color.Yellow);
noBtn.setbackgroundColor(color.blue);
maybeBtn.setbackgroundColor(color.blue);
the above mentioned code is under yesBtn.oncliclListener() method.
yesBtn.setBackgroundColor(getColor(android.R.color.black));
This should do the trick.
Try like this,
Create res/color/button_dark_text.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="#000000" /> <!-- pressed -->
<item android:state_focused="true"
android:color="#000000" /> <!-- focused -->
<item android:color="#FFFFFF" /> <!-- default -->
</selector>
In layout xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="you text"
android:textColor="#color/button_dark_text" />
My Fragment to populate ListView
it works fine when i am using it without List Array , but simple String[] have fixed size , i want to populate a arraylist and then convert it to String[] and then provide it to listAdapter as listAdapter accepts String[].
but after converting Arraylist to String[] , it gives exception
public class FragmentTab2 extends SherlockFragment {
private static String url_all_products = "http://192.168.0.104/StepIn/get_all_products.php";
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "uid";
private static final String TAG_NAME = "unik";
private static final String TAG_profile = "uprofile";
private static final String TAG_location = "ulocation";
private static final String TAG_isactive = "uisactive";
private static final String TAG_gcm = "ugcm";
JSONArray products = null;
List<String> _nik = new ArrayList<String>(); //get data from JSON
String[] myid=new String[5];
String[] nik;
String[] profile=new String[5];
String[] location=new String[5];
String[] isactive=new String[5];
String[] gcm=new String[5];
ListView list;
Activity activity;
ProgressDialog pDialog;
View rootView;
int d=0;
int a=0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragmenttab2, container, false);
new LoadAllProducts().execute();
/* pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Users..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show(); */
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run(){
// do something
}
}, 3000);
// pDialog.dismiss();
// if(nik[0]!=null)
// {
CustomListAdapter adapter=new CustomListAdapter(getActivity(), nik,profile);
list=(ListView)rootView.findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
int n=+position;
//Toast.makeText(getActivity().getApplicationContext(), Slecteditem, Toast.LENGTH_SHORT).show();
Intent i = new Intent (getActivity(),ChatBubbleActivity.class );
i.putExtra("nik", nik[n]);
i.putExtra("id", myid[n]);
i.putExtra("gcm", gcm[n]);
startActivity(i);
}
});
//}
// else
//{
// Toast.makeText(getActivity(), "Plz refresh !\n no user found"+a, Toast.LENGTH_LONG).show();
//}
return rootView;
}
/////////////////////////background////////////////////////////////////////
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* 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, "POST", 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
_nik.add(c.getString(TAG_NAME));
//nik[i]=c.getString(TAG_NAME);
myid[i] = c.getString(TAG_PID);
profile[i] = c.getString(TAG_profile);
location[i] = c.getString(TAG_location);
isactive[i] = c.getString(TAG_isactive);
gcm[i] = c.getString(TAG_gcm);
d++;
// creating new HashMap
//HashMap<String, String> map = new HashMap<String, String>();
}
nik = new String[_nik.size()-1];
a= _nik.size();
int b=d;
b=a;
nik= _nik.toArray(nik);
} else {
// no products found
// Launch Add New product Activity
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute() {
}
}
My Custom Adapter
public class CustomListAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] itemname;
private final String[] imgid;
String my="";
public CustomListAdapter(Context context, String[] itemname, String[] imgid) {
super(context, R.layout.mylist, itemname);
// TODO Auto-generated constructor stub
this.context=context;
this.itemname=itemname;
this.imgid=imgid;
}
public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView=inflater.inflate(R.layout.mylist, null,true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
TextView extratxt = (TextView) rowView.findViewById(R.id.textView1);
txtTitle.setText(itemname[position]);
my=imgid[position];
Bitmap myy= ImageEncoder.StringToBitMap(my);
imageView.setImageBitmap(myy);
extratxt.setText("Description "+itemname[position]);
return rowView;
};
}
logCat
Logs
Here:
CustomListAdapter adapter=new CustomListAdapter(getActivity(), nik,profile);
nik and profile both is null because AsyncTask is asynchronous call which will run in background without stop to execute next line after calling execute method.
so, use onPostExecute method for creating CustomListAdapter object and setting Adapter to ListView.
override onPostExecute method in LoadAllProducts class:
#Override
protected void onPostExecute(String result) {
super.onPostExecute();
// create and set Adapter for ListView here
CustomListAdapter adapter=
new CustomListAdapter(getActivity(), nik,profile);
list.setAdapter(adapter);
}
I am developing an android application ,In that i have 3 tabs namely,
1.Invitation tab(it have the invitation listviews)
2.Event tab(it have the event listviewes)
3.Groupchat tab(it have both invitation and event listviewes)
I have a dropdown(that present on dashboard layout) in gropchat tab that have 3 items namely(All,Event,Invitation).Now my need is,I want to filter my Listviews in Groupchat tab based on Dropdown item click functionality(for example,when on tap "Event" item i need to display only the event listviewes).How can i achieve this,Please help me.
My programming code is below,
public class GroupChatFragment extends Fragment {
private Context context;
private ListView chatListView;
private TextView chatTitle;
private TextView chatPlace;
private TextView chatDate;
private String dateResult;
private List<EventMO> groupEventMoList = new ArrayList<>();
private List<EventMO> eventMOs = new ArrayList<>();
private List<EventMO> invitationMOs = new ArrayList<>();
private EventDelegates eventDelegates = new EventDelegates();
private Gson gson = new Gson();
private ProgressDialog prgDialog;
private ChatDisplayAdapter chatDisplayAdapter;
private ListView GroupEventView;
private SharedPreferences sharedpreferences;
private TextView eventList;
private MessageMO messageMO = new MessageMO();
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.all:
return true;
case R.id.event:
return true;
case R.id.invitation:
return true;
}
return super.onOptionsItemSelected(item);
}
public void Event() {
context = getActivity().getApplicationContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
final UserMO userMO = dbHelper.getRingeeUserData(1);
eventMOs = gson.fromJson(eventDelegates.getAllEventFromUser(userMO, context), new TypeToken<List<EventMO>>() {
}.getType());
List<EventMO> groupEventMOList = new ArrayList<>();
for (EventMO eventMO : eventMOs) {
groupEventMOList.add(eventMO);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final View view = inflater.inflate(R.layout.chatwindow_tab, container, false);
context = getActivity().getApplicationContext();
sharedpreferences = context.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME,
Context.MODE_PRIVATE);
DatabaseHelper dbHelper = new DatabaseHelper(context);
final UserMO userMO = dbHelper.getRingeeUserData(1);
prgDialog = new ProgressDialog(getActivity());
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
prgDialog.show();
//inviation group for user
new AsyncTask<Void, Void, List<EventMO>>() {
#Override
protected List<EventMO> doInBackground(Void... arg0) {
eventMOs = gson.fromJson(eventDelegates.getAllEventFromUser(userMO, context), new TypeToken<List<EventMO>>() {
}.getType());
invitationMOs = gson.fromJson(eventDelegates.getAllEventForUser(userMO, context), new TypeToken<List<EventMO>>() {
}.getType());
List<EventMO> groupEventMOList = new ArrayList<>();
for (EventMO eventMO : eventMOs) {
groupEventMOList.add(eventMO);
}
for (EventMO eventMO : invitationMOs) {
groupEventMOList.add(eventMO);
}
return groupEventMOList;
}
#Override
protected void onPostExecute(List<EventMO> groupEventMOList) {
groupEventMoList = groupEventMOList;
prgDialog.dismiss();
DatabaseHelper dbHelper = new DatabaseHelper(context);
//long totalInsertion = dbHelper.insertUserRelationTable(userMOs);
//Toast.makeText(context, "total userMos size " + userMOs.size() + "total db insertion size " + totalInsertion, Toast.LENGTH_LONG).show();
GroupEventView = (ListView) view.findViewById(R.id.chat_list_view);
chatDisplayAdapter = new ChatDisplayAdapter();
GroupEventView.setAdapter(chatDisplayAdapter);
GroupEventView.setItemsCanFocus(true);
GroupEventView.setTextFilterEnabled(true);
GroupEventView.setOnItemClickListener(GroupEventView.getOnItemClickListener());
}
}.execute(null, null, null);
return view;
}
private class ChatDisplayAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ChatDisplayAdapter() {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return groupEventMoList.size();
}
#Override
public Object getItem(int position) {
return groupEventMoList.get(position);
}
#Override
public long getItemId(int id) {
// for sqllite management
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.chatwindow, null);
convertView.setClickable(true);
convertView.setFocusable(true);
chatTitle = (TextView) convertView.findViewById(R.id.chat_title);
chatPlace = (TextView) convertView.findViewById(R.id.event_place);
chatDate = (TextView) convertView.findViewById(R.id.event_date);
chatPlace.setTextColor(getResources().getColor(R.color.black));
chatDate.setTextColor(getResources().getColor(R.color.black));
chatTitle.setTextColor(getResources().getColor(R.color.black));
chatPlace.setText(groupEventMoList.get(position).getPlace());
String actualDate = groupEventMoList.get(position).getEventDate();
//chatDate.setText(groupEventMoList.get(position).getEventDate());
try {
//date format changed here
Date formatDate = new SimpleDateFormat("yyyy-MM-dd").parse(actualDate);
dateResult = new SimpleDateFormat("dd-MM-yyyy").format(formatDate);
} catch (ParseException e) {
e.printStackTrace();
}
chatDate.setText(dateResult);
chatTitle.setText(groupEventMoList.get(position).getText());
convertView.setTag(position);
View v = convertView.findViewById(R.id.chat_window_single);
v.getRootView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("position", v.getTag().toString());
Intent groupAct = new Intent(context, GroupChatActivity.class);
groupAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
groupAct.putExtra("eventMo", groupEventMoList.get(Integer.parseInt(v.getTag().toString())));
startActivity(groupAct);
}
});
}
return convertView;
}
}
}
You should write custom adapter for each Spinner selection, you need to give a category to each one then set data/values of selected categories to the Listview.
I have a class which retrives data from my database and displays it in a listview using simple adapter
public class ViewExs extends ListActivity {
// Progress Dialog
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 = "http://www.lamia.byethost18.com/get_all_ex.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "ID_exercise";
private static final String TAG_NAME = "ID_exercise";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_exs);
// 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 OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(getApplicationContext(), EditProductActivity.class);
startActivity(i);
/* // getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.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(ViewExs.this);
pDialog.setMessage("Loading products. 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 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(getApplicationContext(),
NewProductActivity.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(
ViewExs.this, productsList,
R.layout.item_list_3, new String[] {TAG_NAME},
new int[] { R.id.pid});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
i want to use a custom adapter rather than the simple adapter .. here is my custom adapter
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
TextView textView;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.item_list_3, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.item_list_3, parent, false);
final TextView textView = (TextView) rowView.findViewById(R.id.pid);
textView.setText(values[position]);
return rowView;
}
}
how i do this part of code
ListAdapter adapter = new SimpleAdapter(
ViewExs.this, productsList,
R.layout.item_list_3, new String[] {TAG_NAME},
new int[] { R.id.pid});
// updating listview
setListAdapter(adapter);
in the custom adapter ?
can someone help please ?
Just use the MySimpleArrayAdapter in your method and set the adapter -
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
* */
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(ViewExs.this,
new String[] {TAG_NAME});
// updating listview
setListAdapter(adapter);
}
});
}
Suppose your arrays of values is String[] values, then
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(
ViewExs.this,values);
setListAdapter(adapter);
Hi I used a custom array adapter like the one below, it's just a sample. But I hope it helps. It displays data that was sent to it using an ArrayList from an fragment where it is displayed.
public class MovieAdapter extends ArrayAdapter<Movie> {
private Context context;
private List<Movie> movies;
public MovieAdapter(Context context, List<Movie> movies) {
super(context, R.layout.movie_layout, movies);
this.context = context;
this.movies = movies;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View movieView = convertView;
if (movieView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
movieView = inflater.inflate(R.layout.movie_layout, parent, false);
}
movieView.setTag(movies.get(position));
TextView txtTitle = (TextView) movieView.findViewById(R.id.txtTitle);
TextView txtDate = (TextView) movieView.findViewById(R.id.txtDate);
RatingBar ratingBar = (RatingBar) movieView
.findViewById(R.id.ratingBar);
txtTitle.setText(movies.get(position).MovieTitle);
txtDate.setText("Date Viewed: " + movies.get(position).dateViewed);
ratingBar.setIsIndicator(true);
ratingBar.setNumStars(movies.get(position).rating);
ratingBar.setRating(movies.get(position).rating);
return movieView;
}
}
The fragment
public class MyListFragment extends Fragment {
Movie movie;
MovieAdapter adapter;
MovieSelectedListener callBack;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_fragment, container, false);
ListView movieList = (ListView) view.findViewById(R.id.movieList);
movieList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
TextView movie = (TextView) view.findViewById(R.id.txtTitle);
String title = movie.getText().toString();
callBack.onMovieSelected(title);
}
});
if (getArguments() != null)
movie = (Movie) getArguments().getSerializable("Movie");
Log.v("PASSED", "Got here");
adapter = new MovieAdapter(getActivity(), movie.movies);
movieList.setAdapter(adapter);
movieList.setLongClickable(true);
movieList.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent,
final View view, int position, long id) {
// TODO Auto-generated method stub
AlertDialog.Builder dialog = new AlertDialog.Builder(
getActivity());
dialog.setMessage("Are you sure you want to delete this movie?");
dialog.setTitle("Alert Message");
dialog.setCancelable(false);
dialog.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
TextView movie = (TextView) view
.findViewById(R.id.txtTitle);
String title = movie.getText().toString();
callBack.onDeleteSelected(title, adapter);
}
});
dialog.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
});
dialog.show();
return false;
}
});
return view;
}
public interface MovieSelectedListener {
public void onMovieSelected(String movie);
public void onDeleteSelected(String movie, MovieAdapter adapter);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
;
try {
callBack = (MovieSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement MovieSelectedListener");
}
}
public void sortTitle() {
adapter.sort(new Comparator<Movie>() {
public int compare(Movie lhs, Movie rhs) {
return lhs.MovieTitle.compareTo(rhs.MovieTitle);
}
});
adapter.notifyDataSetChanged();
}
public void sortDateViewed() {
adapter.sort(new Comparator<Movie>() {
public int compare(Movie lhs, Movie rhs) {
return lhs.dateViewed.compareTo(rhs.dateViewed);
}
});
adapter.notifyDataSetChanged();
}
public void sortRating() {
adapter.sort(new Comparator<Movie>() {
public int compare(Movie lhs, Movie rhs) {
return ((Integer) lhs.rating).compareTo(rhs.rating);
}
});
adapter.notifyDataSetChanged();
}
}