Android: Refresh Listview Item upon clicking spinner Item - android

Hello guys I have this problem, I want my app to refresh or update the listview items upon clicking a specific spinner item. here is the screenshot
and I have no idea on what I'm gonna do, and this is my code so far :(
public class ViewGrade extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private ListView mylistView;
private String subj_code = "";
private String subj_code_lab = "";
private Spinner spinTerm;
private List<GradeList> gradeList = new ArrayList<GradeList>();
private GradeAdapter arrayAdapter;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_grade);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
spinTerm = (Spinner) findViewById(R.id.spinTerm);
String[] Term = new String[]{"Prelim", "Midterm", "Tentative Final"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, Term);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinTerm.setAdapter(adapter);
SharedPreferences preferences = getSharedPreferences("MyApp", MODE_PRIVATE);
subj_code = preferences.getString("code", "UNKNOWN");
subj_code_lab = preferences.getString("code_lab", "UNKNOWN");
mylistView = (ListView) findViewById(R.id.list);
arrayAdapter = new GradeAdapter(this, gradeList);
mylistView.setAdapter(arrayAdapter);
new loadGrades().execute();
}
public class loadGrades extends AsyncTask<Void, Void, Void>{
String term = spinTerm.getSelectedItem().toString();
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewGrade.this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String url = null;
try {
url = "http://192.168.22.3/MobileClassRecord/getGrade.php?subj_code="+ URLEncoder.encode(subj_code, "UTF-8")+"&term="+URLEncoder.encode(term, "UTF-8");
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(url, ServiceHandler.GET);
Log.e("Response; ", "> " + json);
if (json != null){
try {
JSONObject object = new JSONObject(json);
if (object != null){
JSONArray grade_array = object.getJSONArray("grade");
for (int i = 0; i < grade_array.length(); i++){
JSONObject grade = (JSONObject) grade_array.get(i);
GradeList grade_list = new GradeList();
grade_list.setName(grade.getString("stud_name"));
grade_list.setGrade(grade.getString("grade"));
grade_list.setRemark(grade.getString("remark"));
gradeList.add(grade_list);
}
}
arrayAdapter.notifyDataSetChanged();
}catch (JSONException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_view_grade, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
Intent intent = new Intent(ViewGrade.this, SpecificClassRecord.class);
startActivity(intent);
return true;
case R.id.action_add_grade:
Intent intent1 = new Intent(ViewGrade.this, Grade.class);
startActivity(intent1);
}
return super.onOptionsItemSelected(item);
}
}

adapter.notifydatasetChanged() or if you know the specific item inserted/removed, just use adapter.notifyitemInserted/Removed etc.
Add this code in your onClickListener for spinner

Override onItemClick() listener method of the spinner,then inside the method you call adapter.notifydatasetChanged() of the listview

spinTerm.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// change the adapter values if your list is being changedin anyway
arrayAdapter.notifydatasetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});

Related

How to implement onStop() method on a ListView?

I have a ListView on my android app. When click a ListView item and go to a new activity and when i press back button i land on a empty ListView. I dont get any data. Even if i restart the app i dont get any data on the ListView. It works only the first time i run the app. Do i have to override the onStop method and reset my ListView adapter? how do i fix this?
ListView activity
public class ViewGuidesActivity extends AppCompatActivity {
private static final String TAG = ViewGuidesActivity.class.getSimpleName();
private ProgressDialog pDialog;
private List<Guide> guideList = new ArrayList<Guide>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_guides);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, guideList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(AppConfig.URL_GET_GUIDE_LIST,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Guide guide = new Guide();
guide.setNgno(obj.getString("ngno"));
guide.setEmail(obj.getString("email"));
guide.setName(obj.getString("name"));
// adding movie to movies array
guideList.add(guide);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Guide newGuide = guideList.get(position);
String email = newGuide.getEmail();
String ngno = newGuide.getNgno();
Intent i = new Intent(getApplicationContext(), GuideDetails.class);
i.putExtra("email", email);
i.putExtra("ngno", ngno);
startActivity(i);
}
});
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
menu.getItem(1).setVisible(false);
menu.getItem(2).setVisible(false);
return true;
}
}
ListAdapter
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Guide> guideItems;
public CustomListAdapter(Activity activity, List<Guide> guideItems) {
this.activity = activity;
this.guideItems = guideItems;
}
#Override
public int getCount() {
return guideItems.size();
}
#Override
public Object getItem(int location) {
return guideItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.customrow, parent, false);
TextView ngno = (TextView) convertView.findViewById(R.id.txt_ListNgno);
TextView name = (TextView) convertView.findViewById(R.id.txt_ListName);
TextView email = (TextView) convertView.findViewById(R.id.txt_ListEmail);
// getting guide data for the row
Guide g = guideItems.get(position);
//thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
ngno.setText(g.getNgno());
name.setText(g.getName());
email.setText(g.getEmail());
return convertView;
}
}
how do i fix this issue?

How to send ID from an Element on listItems to another View where i wana publish all information of this Element?

This ListView class where i bring different element from my server with help of php and JSON calls to my listview. The problem is i would like to send the ID of element to another view when i click of specific element on listview. and in another View i would like to publish the detail information about the element that i clicked. Any wan have idea about that?
public class Forestillinger extends AppCompatActivity {
ListView dagensaktivitet;
TextView txt;
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
JSONParser jsonParser = new JSONParser();
JSONObject hc = null;
JSONArray fstilling;
public String hk = "";
int success;
String msg;
final Context c = this;
StableArrayAdapter adb;
private static final String url_Forestillinger = "http://barnestasjonen.no/test/db_get_forestillinger.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forestillinger);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dagensaktivitet = (ListView) findViewById(R.id.forestillinglist);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems) {
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView txt = (TextView) view.findViewById(android.R.id.text1);
txt.setTextColor(Color.WHITE);
return view;
}
};
dagensaktivitet.setAdapter(adapter);
Log.d("i oncreate", adapter.toString());
//if(!fromLocalDB())
try {
new getShows().execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
//JSONObject tickets = task.getJSon();
adapter.notifyDataSetChanged();
dagensaktivitet.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), Forestilling.class);
i.putExtra("selectedItem", listItems.get(position));
startActivity(i);
}
});
}
public void fromExtDB() throws JSONException {
fstilling = hc.getJSONArray("forestillinger");
for (int i = 0; i < fstilling.length(); i++) {
listItems.add(fstilling.getJSONObject(i).getString("tittel")+fstilling.getJSONObject(i).getString("id"));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_forestillinger, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void forestillingResult(){
new AlertDialog.Builder(Forestillinger.this)
.setTitle("OBS!!!")
.setMessage(msg)
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
hk = "";
finish();
}
})
.show();
}
private class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
List<Integer> trialId;
public StableArrayAdapter(Context context, int textViewResourceId, List<String> objects, List<Integer> objectId) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); i++)
mIdMap.put(objects.get(i), i);
trialId = objectId;
}
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
public int getActualId(int position)
{
return trialId.get(position);
}
}
class getShows extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
Log.d("TEST", "jeg er her");
List<NameValuePair> params = new ArrayList<NameValuePair>();
//params.add(new BasicNameValuePair("id", "adam#gmail.com"));
//params.add(new BasicNameValuePair("type", "android"));
JSONObject json = jsonParser.makeHttpRequest(url_Forestillinger, "POST", params);
try {
if (json != null) {
success = Integer.parseInt(json.getString("success"));
msg = json.toString();
System.out.println("Vi er her:" + msg + " " + success);
}
if (success == 1) {
hc = json;
System.out.println("jojo"+json.toString());
}
else
{
msg=json.getString("message");
System.out.println(msg);
msg= Html.fromHtml(msg).toString();
hk = msg;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//run code
try {
Log.d("TAG23", "vi er in onpostExecute");
if(success == 1) {
fromExtDB();
}else{
forestillingResult();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
and here is the second view.
public class Forestilling extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forestilling);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*Bundle extras = getIntent().getExtras();
Log.d("TAG:", "" + extras.getInt("TryThis"));*/
Bundle extras = getIntent().getExtras();
String s = extras.getString("selectedItem");
Log.d("TAG:", "" + s);
TextView tit = (TextView)findViewById(R.id.tittel);
TextView dato = (TextView)findViewById(R.id.dato);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_forestilling, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I'm not allowed to flag at this moment, but this might be a duplicate of how can i use the number from textfield of each row in listview and make a call on this number?
Anyway, my answer given there might solve your problem:
Here is what I do:
private class MyAdapter extends BaseAdapter {
private ListView listView;
...
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
this.listView = (ListView) viewGroup;
and then in each View.OnClickListener I can get the position of the clicked item by
#Override
public void onClick(View view) {
...
MyAdapter.this.listView.getPositionForView((View) view.getParent()));

android get rssitem description from listview

In my android app I'm using a ListView populated by RSSItems taken from a webpage url; the listview shows me only title and pubdate of rssitem.
I would realize that when I click on rssitem of the listview, app shows me an alert dialog showing me in message box the descritpion of the rssitem title.
How can I realize it?
Here the code:
public class MainActivity extends ActionBarActivity{
private ListView listview;
URL url = null;
RssFeed feed = null;
AlertDialog.Builder alert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listView);
alert = new AlertDialog.Builder(MainActivity.this);
try {
url = new URL("http://www.unikore.it/index.php/ingegneria-informatica-home?format=feed");
} catch (MalformedURLException e) {
e.printStackTrace();
}
new ReadRssTask().execute(url);
}
private class ReadRssTask extends AsyncTask<URL, Void, RssFeed> {
#Override
protected RssFeed doInBackground(URL... params) {
RssFeed result = null;
URL url = params[0];
if (!TextUtils.isEmpty(url.toString())) {
try {
result = RssReader.read(url);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
#Override
protected void onPostExecute(RssFeed result) {
if (result != null) {
ArrayList<RssItem> rssItems = (ArrayList<RssItem>) result.getRssItems();
ArrayList<String> arrayList = new ArrayList<String>();
for (final RssItem rssItem : rssItems) {
arrayList.add(rssItem.getTitle()+"\n"+rssItem.getPubDate()+"\n");
ArrayAdapter<String> lista = new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1,arrayList);
listview.setAdapter(lista);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
alert.setTitle(listview.getItemAtPosition(position).toString());
alert.setMessage(); //HERE I SHOULD SET THE rssItem.getDescription()
alert.show();
}
});
Log.i("RSS Reader", rssItem.getTitle());
}
}
}
}
}
You need to change here
alert.show();
to
AlertDialog dialog = alert.create(); // You missed this
dialog.show():
Edit:
Remove this from loop and move to onCreate() after your asynctask executed.
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
alert.setTitle(listview.getItemAtPosition(position).toString());
alert.setMessage(rssItems.get(position).getDescription()); //HERE YOU SHOULD SET THE rssItem.getDescription()
alert.show();
}
});
Make this ArrayList<RssItem> rssItems public static and use as
rssItems = (ArrayList<RssItem>) result.getRssItems();

Get the arraylist stored id from the clickable item on the autocompletextview

So my problem is this I need to get the respective "id" field stored in my arrylist that correspond to the selected autocompletextview item and I can't do this. I parse data to a json format and store it in arraylist, and what I want is to click on the dropdown list of the autocompletetextview (already working) item, and get the respective id.
Json Data:
{"estab":[{"id":"00","design":"NULL"},
{"id":"01","design":"Continente de Viana do Castelo"},
{"id":"02","design":"Pingo Doce Viana do Castelo"},
{"id":"03","design":"Pingo Doce - Portuzelo (Viana Castelo)"},
Arraylist get and set:
public class Estbs {
private String id;
private String design;
public String getID() {
return id;
}
public void setID(String id) {
this.id = id;
}
public String getDesign() {
return design;
}
public void setDesign(String design) {
this.design = design;
}
}
main/json function
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ArrayList<String> establist;
ArrayList<Estbs> estab;
String x;
private AutoCompleteTextView actv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_linha);
//Download JSON file AsyncTask
new DownloadJSON().execute();
}
//Download JSON file AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Locate the WorldPopulation Class
estab = new ArrayList<Estbs>();
// Create an array to populate the spinner
establist = new ArrayList<String>();
// JSON file URL address
jsonobject = JSONfunctions
.getJSONfromURL(url_donload_estbs);
try {
// Locate the NodeList name
jsonarray = jsonobject.getJSONArray("estab");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Estbs estabs = new Estbs();
estabs.setID(jsonobject.optString("id"));
estabs.setDesign(jsonobject.optString("design"));
estab.add(estabs);
// Populate spinner with country names
establist.add(jsonobject.optString("design"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the spinner in activity_main.xml
actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
// Spinner adapter
actv
.setAdapter(new ArrayAdapter<String>(Newlin_ProductActivity.this,
android.R.layout.simple_list_item_1,
establist));
// Spinner on item click listener
actv
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// Locate the textviews in activity_main.xml
TextView txtrank = (TextView) findViewById(R.id.design);
// Set the text followed by the position
txtrank.setText("Rank : "
+ estab.get(position).getID());
x = estab.get(position).getID();
Toast.makeText(getApplicationContext(), x,
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
Please check bellow code :-
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
String selection = (String) parent.getItemAtPosition(position);
int id;
for (int i = 0; i < establist.size(); i++) {
if(estab.get(i).getDesign().equals(selection))
{
id=estab.get(i).getId();
break;
}
}
}
In short onItemClicklistener() did the job but i would suggest you to have a look at the code below and try following such practise in daily coding.
public class MainActivity extends Activity implements OnItemClickListener {
private ArrayList<String> establist;
private ArrayList<Estbs> estab;
private AutoCompleteTextView autoCompleteTextView;
private TextView txtRank;
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoComplete);
autoCompleteTextView.setOnItemClickListener(this);
txtRank = (TextView) findViewById(R.id.textView1);
estab = new ArrayList<Estbs>();
establist = new ArrayList<String>();
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
for (int i = 0; i < 10; i++) {
fillDataInEstabs();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
autoCompleteTextView.setAdapter(new ArrayAdapter<String>(
MainActivity.this, android.R.layout.simple_list_item_1,
establist));
}
}
private void fillDataInEstabs() {
Estbs e = new Estbs();
e.setId(String.valueOf(count));
e.setDesign("Hello " + String.valueOf(count));
estab.add(e);
establist.add(e.getDesign());
count++;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
String selection = (String) parent.getItemAtPosition(position);
int actualPosition = estab.indexOf(selection);
txtRank.setText("Rank : " + estab.get(actualPosition).getId());
Toast.makeText(getApplicationContext(), estab.get(actualPosition).getId(),
Toast.LENGTH_LONG).show();
}
}

adding data to existing listview

I have created listview using the following code
public class homeScreen extends Activity{
ArrayList<SingleRow> list;
boolean flag = false;
String space = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
final Context c = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.homescreen);
//putting actual values in array
list = new ArrayList<SingleRow>();
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.titles);
int[] images = {R.drawable.error,R.drawable.ic_launcher,R.drawable.ic_launcher};
//putting single row in arraylist
for(int i = 0;i<3;i++){
list.add(new SingleRow(titles[i], images[i]));
}
final ListView list1 = (ListView)findViewById(R.id.spacelist);
final MySimpleAdapter adapter = new MySimpleAdapter(this,list);
list1.setAdapter(adapter);
space = getIntent().getStringExtra("spaceName");
if(null! = space){
adapter.addView(space);
}
list1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.titles);
if((titles[position]).equalsIgnoreCase("My Ideas")){
Intent i = new Intent(homeScreen.this, privateSpaceList.class);
startActivity(i);
} else if((titles[position]).equalsIgnoreCase("Create New Space")){
Intent i = new Intent(homeScreen.this, createNewSpace.class);
startActivity(i);
}
}
});
}
}
Row class:
class SingleRow{
String title;
int image;
public SingleRow(String title,int image) {
this.title = title;
this.image = image;
}
}
Adapter:
class MySimpleAdapter extends BaseAdapter{
ArrayList<SingleRow> list;
private Context context;
public MySimpleAdapter(Context c,ArrayList<SingleRow> list) {
this.context = c;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public void addView(String space) {
int rows = this.getCount();
list.add(rows, new SingleRow(space,R.drawable.ic_launcher));
notifyDataSetChanged();
}
#Override
public View getView(int i, View view, ViewGroup viewgroup) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row,viewgroup,false);
TextView title = (TextView)row.findViewById(R.id.label);
ImageView image = (ImageView)row.findViewById(R.id.imageView);
SingleRow temp = list.get(i);
title.setText(temp.title);
image.setImageResource(temp.image);
return row;
}
}
code for create new space
public class createNewSpace extends Activity{
Button add;
TextView sname,pname;
ListView plist;
int success;
Jparser jsonParser = new Jparser();
JSONObject json;
private ProgressDialog pDialog;
ArrayList<String> usersList;
ArrayList<String> spaceUsers;
private static String url_users = "http://10.0.2.2/phpdata/getting_allusers.php";
private static String url_create_space = "http://10.0.2.2/phpdata/create_space.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_USERS = "users";
private static final String TAG_UNAME = "firstName";
// products JSONArray
JSONArray users = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.createnewspace);
sname=(TextView)findViewById(R.id.spaceName);
pname=(TextView)findViewById(R.id.participents);
plist=(ListView)findViewById(R.id.participantlist);
add=(Button)findViewById(R.id.button1);
// Hashmap for ListView
usersList= new ArrayList<String>();
spaceUsers=new ArrayList<String>();
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new getAllUsers().execute();
}
});
plist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String users[]=usersList.toArray(new String[usersList.size()]);
Toast.makeText(getApplicationContext(), "User "+users[arg2]+ " added to space "+sname.getText(), Toast.LENGTH_SHORT).show();
spaceUsers.add(users[arg2]);
}
});
// Loading users in Background Thread
}
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menuspace, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
return MenuChoice(item);
}
private boolean MenuChoice(MenuItem item)
{
switch(item.getItemId())
{
case R.id.create:
new createSpace().execute();
return true;
}
return false;
}
class createSpace extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
for(int i=0;i<spaceUsers.size();i++)
{
String sname1 = sname.getText().toString();
String uname = spaceUsers.get(i);
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sname", sname1));
params.add(new BasicNameValuePair("uname", uname));
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(url_create_space,
"POST", params);
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully inserted user details
Intent is = new Intent(getApplicationContext(), homeScreen.class);
is.putExtra("spaceName", sname1);
startActivity(is);
// closing this screen
finish();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
}
}
class getAllUsers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON Object
json = jsonParser.makeHttpRequest(url_users,"GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// getting value of success tag
try {
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
if (success == 1) {
// Getting Array of users
try{
JSONArray users=json.getJSONArray(TAG_USERS);
// looping through All Products
for (int i = 0; i < users.length(); i++) {
Log.d("check", "success");
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_UNAME);
Log.d("name....",name);
// adding HashList to ArrayList
usersList.add(name);
}
} catch(JSONException e)
{
e.printStackTrace();
}
}
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
plist.setAdapter(new ArrayAdapter<String>(createNewSpace.this,android.R.layout.simple_list_item_1,usersList));
}
});
}
}
}
Now I want to add Item to this existing list.
I am taking data from another activity using intent.
Now one item get added.but next time that get replaced.
Please Help.
Thank you in advance.
You should move the creation of the data outside of the adapter:
list=new ArrayList<SingleRow>();
//putting actual values in array
Resources res=c.getResources();
String[] titles=res.getStringArray(R.array.titles);
int[] images={R.drawable.error,R.drawable.ic_launcher,R.drawable.ic_launcher};
//putting single row in arraylist
for(int i=0;i<3;i++){
list.add(new SingleRow(titles[i], images[i]));
}
Pass the list variable to the adapter and store a reference to it there. Then you can just update the data in the list variable, and call notifyDataSetChanged() on your adapter.
Edit: It seems you want to store the space values, and then retrieve them in the HomeScreen activity later. If I understand the flow of your app correctly, then the createNewSpace class should store the space in SharedPreferences. Then in the HomeScreen activity you should retrieve those from the SharedPreferences, and show them.
You can add data to the adapter and call notifyDataSetChanged().Alternatively, You can create a new adapter and listView.setAdapter(adapter) that adapter.

Categories

Resources