Use Hashmap for ListView Android - android-listview

I have some problem with my code, I want to display the results from con.execute into the ListView
How to use this Hashmap for Listview?
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_log, container, false);
// Untuk menjalankan API Mikrotik
ApiConnection con = MainActivity.getCon();
if (con !=null) {
try {
List<Map<String, String>> rs = con.execute("/log/print");
for (Map<String, String> r : rs) {
ListView listView = (ListView) view.findViewById(R.id.viewLog);
ArrayAdapter<String> listViewAdapter = new ArrayAdapter<String>(
getActivity(),
android.R.layout.simple_list_item_1);
listView.setAdapter(listViewAdapter);
}
} catch (MikrotikApiException e) {
e.printStackTrace();
}
}
return view;
}

Related

Arrayadapter only returning the last element

I'm new to android development and right now I'm trying to parse an J SON array into object and then save each object into a array list then display the array list with a array adapter. But, right now I can only get the array adapter to display the last element.
Here is the main class
public class Venue extends Activity {
Venue_Listing venue = new Venue_Listing();
ArrayList<Venue_Listing> venueList;
ListView listview;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.list);
new GetVenus().execute(URL);
venueList = new ArrayList<Venue_Listing>();
}
private class GetVenus extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
String data;
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Venue.this);
dialog.setMessage("Loading, please wait");
dialog.show();
dialog.setCancelable(false);
}
protected Boolean doInBackground(String... url) {
try {
HttpGet httppost = new HttpGet(url[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
data = EntityUtils.toString(entity);
}
return true;
}
catch (ParseException e1) {
e1.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
Venue_Listing_Adapter adapter = new
Venue_Listing_Adapter(getApplicationContext(),R.layout.venue_list_layout, venueList);
try {
JSONArray jarray = new JSONArray(data);
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
if (venue != null) {
venue.SET_ID(object.getString("venue_ID"));
venue.SET_NAME(object.getString("name"));
listview.setAdapter(adapter);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
}
This class holds all the J SON parse data
public class Venue_Listing {
private String ID;
private String NAME;
public Venue_Listing() {
}
public Venue_Listing(String ID, String NAME) {
super();
this.ID = ID;
this.NAME = NAME;
}
// setter & getter....
And here is what I have for my array adapter
public class Venue_Listing_Adapter extends ArrayAdapter<Venue_Listing> {
private ArrayList<Venue_Listing> objects;
public Venue_Listing_Adapter(Context context, int resource, ArrayList<Venue_Listing> objects) {
super(context, resource, objects);
this.objects = objects;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.venue_list_layout, null);
}
Venue_Listing i = objects.get(position);
if (i != null) {
TextView id = (TextView) v.findViewById(R.id.id);
TextView name = (TextView) v.findViewById(R.id.name);
if (id != null ){
id.setText(i.GET_ID());
}
if (name != null) {
name.setText(i.GET_NAME());
}
}
return v;
}
}
Any help would be appreciated
Thank you
Please print and check the values of 'venueList'.
You have not added values in 'venueList' object.
You need to create 'venue' object every time and add object 'venue' in 'venueList'. Hence you are not getting all items in list view.
The Code may go this way: -
Venue_Listing venue;
try {
JSONArray jarray = new JSONArray(data);
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
venue = new Venue_Listing();
if (object != null) {
venue.SET_ID(object.getString("venue_ID"));
venue.SET_NAME(object.getString("name"));
venueList.add(venue);
}
}
Venue_Listing_Adapter adapter = new Venue_Listing_Adapter(getApplicationContext(),R.layout.venue_list_layout, venueList);
listview.setAdapter(adapter);
}
catch (JSONException e) {
e.printStackTrace();
}

Passing Text From Listview to another Activity when I click action item of the listview

I have a listview in my main activity.In each row i have a image view,when i click that image view QuickAction(Like popover in ios) will appears.My request is, I want to setText the text from listview to the another Activity's edittext when i click the action item in the quick action.Please help..
Here is my Main Activity
public class ExampleActivity extends Activity {
private static final int ID_UP = 1;
private static final int ID_DOWN = 2;
private static final int ID_SEARCH = 3;
private static final int ID_INFO = 4;
private QuickAction quickAction;
private ActionItem nextItem;
private ActionItem prevItem;
private ActionItem searchItem;
private ListView view;
private ContactsAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
view = (ListView) findViewById(R.id.listView1);
final Weather weather_data[] = new Weather[] { new Weather(R.drawable.icon, "Cloudy"),
new Weather(R.drawable.icon, "Showers"),
new Weather(R.drawable.icon, "Snow"),
new Weather(R.drawable.icon, "Storm"),
new Weather(R.drawable.icon, "Sunny")
};
adapter = new ContactsAdapter(this, R.layout.main1,
weather_data);
}
void functiontorun(View view1) {
quickAction = new QuickAction(this,QuickAction.HORIZONTAL);
nextItem = new ActionItem(ID_DOWN, "Next", getResources().getDrawable(
R.drawable.menu_down_arrow));
prevItem = new ActionItem(ID_UP, "Prev", getResources().getDrawable(
R.drawable.menu_up_arrow));
searchItem = new ActionItem(ID_SEARCH, "Find", getResources()
.getDrawable(R.drawable.menu_search));
// use setSticky(true) to disable QuickAction dialog being dismissed
// after an item is clicked
prevItem.setSticky(true);
nextItem.setSticky(true);
// add action items into QuickAction
quickAction.addActionItem(nextItem);
quickAction.addActionItem(prevItem);
quickAction.addActionItem(searchItem);
// Set listener for action item clicked
final int position1 = view.getPositionForView(view1);
quickAction
.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
#Override
public void onItemClick(QuickAction source, int pos,
int actionId) {
ActionItem actionItem = quickAction.getActionItem(pos);
if (actionId == ID_SEARCH) {
Intent i=new Intent(ExampleActivity.this,Second.class);
i.putExtra("position",position1 );
Log.v("position","po" +position1);
startActivity(i);
} else if (actionId == ID_INFO) {
Toast.makeText(getApplicationContext(),
"I have no info this time",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
actionItem.getTitle() + " selected",
Toast.LENGTH_SHORT).show();
}
}
});
quickAction.show(view1);
}
}
And my another activity
public class Second extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
EditText d1=(EditText) findViewById(R.id.editText1);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
final int position = (Integer) bundle.get("position");
Log.v("position","po1 " +position);
ArrayList<Weather> array = new ArrayList<Weather>();
Log.v("position","po1 " +array);
}
}
}
contacts adapter:
public class ContactsAdapter extends ArrayAdapter{
Context context;
int layoutResourceId;
Weather data[] = null;
public ContactsAdapter(Context context, int layoutResourceId, Weather[] 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;
WeatherHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imageView1);
holder.imgIcon.findViewById(R.id.imageView1).setOnClickListener(mBuyButtonClickListener);
holder.txtTitle = (TextView)row.findViewById(R.id.textView1);
//((ImageView) row.findViewById(R.id.im)).setOnClickListener(mBuyButtonClickListener);
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
Weather weather = data[position];
holder.txtTitle.setText(weather.title);
holder.imgIcon.setImageResource(weather.icon);
return row;
}
static class WeatherHolder
{
ImageView imgIcon;
TextView txtTitle;
}
private OnClickListener mBuyButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
((ExampleActivity) context).functiontorun(v);
}
};
}
private OnClickListener mBuyButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
WeatherHolder holder = (WeatherHolder) v.getTag;
String string = holder.txtTitle .getText();
((ExampleActivity) context).functiontorun(string);
}
};
just pass the string to your activity and change the parameter of the functiontorun as string

Refresh ListView when Device receives GCM IntentService Message

My app is able to receive messages from GCM and saves the messages to the SQLlite database on the phone. The messages are viewable in a activity that has a listview.
In the code below, the onPause() function refreshes the listView. This is not a good implementation because it only works if the activity is not displayed at the time of the update. If the activity is displayed at the time of an update, the list is static and does not update.
Questions:
How to I update the listview when the activity is being displayed? Or is there a way to use a background service to update the adapter, so that whenever the activity is displayed, it always shows the newest data.
is this kind of functionality currently not possible with android and I'll need to implement something else like 'pull-to-refresh'?
refreshing listview in OnResume() crashes the application, and shows a null pointer exception.
Activity:
public class NotesView extends Activity implements OnItemClickListener {
ListView listView;
NoteAdapter objAdapter;
NotificationsDatabase db = new NotificationsDatabase(this);
List<Notes> listAlerts;
String note;
String time;
TextView noteView;
TextView timeView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
new MyTask().execute();
}
// My AsyncTask start...
class MyTask extends AsyncTask<Void, Void, List<Notes>> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NotesView.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
if (isCancelled()) {
this.cancel(true);
}
}
#Override
protected List<Notes> doInBackground(Void... params) {
db.open();
listAlerts = db.getData();
if (isCancelled()) {
this.cancel(true);
}
return null;
}
protected void onPostExecute(List<Notes> alerts) {
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
db.close();
setAdapterToListview();
}
}// end myTask
public void setAdapterToListview() {
objAdapter = new NoteAdapter(NotesView.this, R.layout.row_notes, listAlerts);
objAdapter.sortByNoteDesc();
objAdapter.notifyDataSetChanged();
listView.setAdapter(objAdapter);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
Intent intent = new Intent(
NotesView.this.getApplicationContext(),
TabBarExample.class);
intent.putExtra("goToTab", "Alerts");
startActivity(intent);
return true;
}
return super.onKeyDown(keyCode, event);
}
public void onItemClick(AdapterView<?> parent, View viewDel, int position,
long id) {
for (int i = 0; i < 1; i++) {
Notes item = listAlerts.get(position);
int ids = item.getId();
note = item.getNote();
time = item.getTimeStamp();
}
System.out.println(note + " " + time);
//
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setAdapter(null);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
new MyTask().execute();
}
#Override
protected void onDestroy() {
}
}
Code snippets From GCMIntentService
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
//String message = getString(R.string.gcm_message);
System.out.println("onMessage: ");
Bundle extras = intent.getExtras();
String message = extras.getString("message");
String event_id_from_server = extras.getString("server_id");
// displayMessage(context, message);
generateNotification(context, message);
saveMsg(message);
System.out.println("server id is " + event_id_from_server);
if (event_id_from_server != null) {
updateLocalDatabase(event_id_from_server);
}
}
public void saveMsg(String msg) {
boolean worked = true;
try {
NotificationsDatabase entry = new NotificationsDatabase(GCMIntentService.this);
entry.open();
java.util.Date date = new java.util.Date();
Timestamp x = new Timestamp(date.getTime());
String timeStamp = x.toLocaleString();
entry.createEntry(msg, timeStamp);
entry.close();
//update adapter service
} catch (Exception e) {
worked = false;
String error = e.toString();
System.out.println(error);
} finally {
if (worked) {
}
}
}
I cleaned up your code a little bit. Basically all the view assignments should be done once in onCreate, while the loading of the data should be done in onResume(). See if this helps:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setAdapter(null);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
}
#Override
protected void onResume() {
super.onResume();
new MyTask().execute();
}
#Override
protected void onPause() {
super.onPause();
}

setOnItemClickListener in customized listview

Here is the activity ShowData.java where i am setting up customized listview.. Now i need to click view on that listview and need to display another activity but throws force close.. It throws error on listview.setAdapter(adapter);
public class ShowData extends Activity
{
ListView listview;
Intent intent;
ArrayList<BeanClass> datalist;
CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
listview = (ListView) findViewById(R.id.listView1);
Intent intent = getIntent();
datalist = (ArrayList<BeanClass>) intent.getSerializableExtra("list");
Log.i("Size of ArrayList", "is " +datalist.size());
adapter = new CustomAdapter(ShowData.this, R.layout.customrow , datalist);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
{
Intent i = new Intent(ShowData.this,DetailActivity.class);
i.putExtra("datalist", datalist);
i.putExtra("position", arg2);
startActivity(i);
}
}
}
Here is the CustomAdapter.java
public class CustomAdapter extends ArrayAdapter<BeanClass>
{
Context context;
int layoutResourceId;
BeanClass bc;
ArrayList<BeanClass> vbc;
public CustomAdapter(Context context, int layoutResourceId, ArrayList<BeanClass> vbc)
{
super(context, layoutResourceId, vbc);
this.context=context;
this.layoutResourceId=layoutResourceId;
this.vbc=vbc;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
StringReaderHolder holder;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent,false);
holder= new StringReaderHolder();
holder.mytext1 = (TextView) row.findViewById(R.id.textView1);
holder.mytext2 = (TextView) row.findViewById(R.id.textView2);
holder.mytext3 = (TextView) row.findViewById(R.id.textView3);
row.setTag(holder);
}
else
{
holder = (StringReaderHolder) row.getTag();
}
BeanClass bsObject = vbc.get(position);
holder.mytext1.setText(bsObject.name);
holder.mytext2.setText(bsObject.address);
holder.mytext3.setText(bsObject.phone);
return row;
}
static class StringReaderHolder
{
TextView mytext1,mytext2,mytext3;
}
}
How should i use setOnItemClickListener...??? Thanks...
In Your getView Method try:
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(context,DetailActivity.class);
i.putExtra("datalist", vbc);
i.putExtra("position", position);
startActivity(i);
}
});

What's the problems when I use ".getText().toString();"

#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText nameText = (EditText) findViewById(R.id.editText1);
name = nameText.getText().toString();
nameText.setText("");
EditText numberText = (EditText) findViewById(R.id.editText2);
number = numberText.getText().toString();
numberText.setText("");
person = new Person(name, number);
order.add(person);
PersonAdapter pa = new PersonAdapter(con, R.layout.row, order);
setListAdapter(pa);
}
});
}
#Override
protected void onListItemClick(ListView l, View v, final int position, long id) {
// TODO Auto-generated method stub
final int index = position;
AlertDialog.Builder aDialog = new AlertDialog.Builder(this);
aDialog.setTitle("What do you want??");
aDialog.setPositiveButton("Delete",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
order.remove(index);
PersonAdapter pa = new PersonAdapter(con, R.layout.row,
order);
setListAdapter(pa);
}
});
aDialog.setNeutralButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) con.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog, (ViewGroup)findViewById(R.id.root_layout));
builder = new AlertDialog.Builder(con);
builder.setView(layout);
builder.setTitle("Fill EditText");
builder.setIcon(R.drawable.icon);
editNum = (EditText)findViewById(R.id.editNum);
editName = (EditText)findViewById(R.id.editName);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
name = editName.getText().toString();
number = editNum.getText().toString();
order.set(position, new Person(name,number));
PersonAdapter pa = new PersonAdapter(con, R.layout.row, order);
setListAdapter(pa);
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alertDialog = builder.create();
alertDialog.show();
}
});
aDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
AlertDialog ad = aDialog.create();
ad.show();
}
public PersonAdapter(Context context, int textViewResourceId,
ArrayList<Person> items) {
super(context, textViewResourceId, items);
this.items = items;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
}
Person p = items.get(position);
if (p != null) {
TextView tt = (TextView) v.findViewById(R.id.android_toptext);
TextView bt = (TextView) v.findViewById(R.id.android_bottomtext);
if (tt != null) {
tt.setText(p.getName());
}
if (bt != null) {
bt.setText("TEL : " + p.getNumber());
}
}
return v;
}
private String name;
private String number;
public Person(String name, String number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
}
I am practicing Widget(exactly I am making custom dialog) and Listener In android . But I stop now because ".getText().toString();" makes error ... I can't understand.. T^T Please Help me... why it makes error?? I think It doesn't have problem
You should declare your EditText globally
EditText editName;
EditText editNum;
#Override
public void onCreate(Bundle savedInstanceState) {
...
}
.....
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) con.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog, (ViewGroup)findViewById(R.id.root_layout));
builder = new AlertDialog.Builder(con);
builder.setView(layout);
builder.setTitle("Fill EditText modificated");
builder.setIcon(R.drawable.icon);
editName = (EditText)findViewById(R.id.editName);
editNum = (EditText)findViewById(R.id.editNum);