So I managed to save data from an array in a json file. This array is created manually as you can see by the 8 item.add(...) and each item has 4 values. isSelected, userName, userAttack, userStatus and isFavorite. Only isSelected and isFavorite will change through onItemClickListeners and are of type boolean. I want to store the change of those values as soon as I click on the item and it worked. The Logs would show me that json is an array with all the information inside.
My Problem is the retrieval of this information when the app is created and I have no idea where to place it. Not only that but I dont know how to use the json file in onCreate because the json is only made when I click or longclick on the items. Can somebody give me hints on how to successfully let the app remember that values the item has? Would be very thankful.
//package and imports
public class MainActivity extends Activity {
ListView listView;
private String msg = "Android : ";
private boolean isChecked;
ArrayList<UserModel> item = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<UserModel> item = new ArrayList<>();
listView = (ListView) findViewById(R.id.list_view);
item.add(new UserModel(false, R.string.name0, R.string.atk0, R.string.stat0,false));
item.add(new UserModel(false, R.string.name1, R.string.atk1, R.string.stat1,false));
item.add(new UserModel(false, R.string.name2, R.string.atk2, R.string.stat2,false));
item.add(new UserModel(false, R.string.name3, R.string.atk3, R.string.stat3,false));
item.add(new UserModel(false, R.string.name4, R.string.atk4, R.string.stat4,false));
item.add(new UserModel(false, R.string.name5, R.string.atk5, R.string.stat5,false));
item.add(new UserModel(false, R.string.name6, R.string.atk6, R.string.stat6,false));
item.add(new UserModel(false, R.string.name7, R.string.atk7, R.string.stat7,false));
Log.d(msg, "Made UserModel List with size: " + item.size());
final CustomAdapter adapter = new CustomAdapter(this, item);
listView.setAdapter(adapter);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.d(msg,"Item " + i + " was long clicked!");
UserModel model = item.get(i);
if(model.isFavorite()) {
model.setFavorite(false);
Log.d(msg, "Item " + i + " was removed as Favorite!");
Toast.makeText(view.getContext(), model.getUserName() + i + " was removed from Favorites!", Toast.LENGTH_SHORT).show();
} else {
model.setFavorite(true);
Log.d(msg, "Item " + i + " was added as Favorite!");
Toast.makeText(view.getContext(),model.getUserName() + i + " was added to Favorites!",Toast.LENGTH_SHORT).show();
}
item.set(i, model);
adapter.updateRecords(item);
Gson gson = new Gson();
String json = gson.toJson(item);
Log.d(msg, "Here is the json file: " + json);
return model.isFavorite();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.d(msg, "Item " + (i) + " was clicked!");
UserModel model = item.get(i);
if (model.isSelected())
model.setSelected(false);
else
model.setSelected(true);
Log.d(msg, "Item " + (i) + " " + model.isSelected());
item.set(i, model);
//now update adapter
adapter.updateRecords(item);
Gson gson = new Gson();
String json = gson.toJson(item);
Log.d(msg, "Here is the json file: " + json);
}
});
}
}
Assuming I understood your question, here is how you can load the json data onCreate.
ArrayList<UserModel> items = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Load json to string from the file you saved it in
...
String rawJson = "...";
//Parse data to your list
...
items = gson.fromJson(br, new TypeToken<List<UserModel>>(){}.getType());
}
However, I would recommend looking into storing your data in a local database, as it is easier to update and manage. Storing json in a file is very ugly.
You could check out libraries as Room.
Related
Hi in the below code how to get names of the below JSON responses from users object.want to display the names and setting to the spinner adapter.
can anyone help me
expected output:
Admin Administrator
Ganeshprasad S etc
response:
{
"name": "assigned_user_id",
"label": "Assigned To",
"mandatory": true,
"type": {
"name": "owner",
"users": {
"19x1": "Admin Administrator",
"19x5": "Ganeshprasad S",
"19x6": "Balaji RR",
"19x7": "Kiran Thadimarri",
"19x8": "Sridhar Balakrishnan",
"19x9": "Shilpa MK",
"19x10": "Velmurugan N",
"19x11": "Aamir Khanna",
"19x12": "Jamir Abbas Pinjari",
"19x13": "Syed Shadab Ashraf",
"19x14": "Shahul Hameed",
"19x15": "Manjula C",
"19x16": "Keerthi Vasan L",
"19x17": "Lochan Jyoti Borgohain",
"19x18": "Rajkumar Sanatomba Singh",
"19x19": "Krishna Pandey",
"19x20": "Nabajit Pathak",
"19x21": "Manoranjan Ningthoujam",
"19x22": "Pravin Karbhari Ahire",
"19x23": "Pratap Kumar Choudhary"
}
}
}
below is code .nothing was displaying for the spinner
java:
if (name.equals("assigned_user_id")) {
String jsondata ="";
try {
JSONObject jsonobj = new JSONObject(jsondata);
JSONObject type = jsonobj.getJSONObject("type");
JSONObject usr = type.getJSONObject("users");
Iterator<String> keys = usr.keys();
while(keys.hasNext()) {
String key = keys.next();
if (jsonobj.get(key) instanceof JSONObject) {
String v = usr.getString("19x1");
account_manger.add(v);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, account_manger);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinneraccountManager.setAdapter(dataAdapter);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Lets say your JSON data is in String
String jsondata ;
JSONObject jsonobj = new JSONObject(jsondata);
Since this json object has many properties so we will get the property "type" which is of type Object, So we will create another object of JSONObject
JSONObject type = jsonobj.getJSONObject("type");
Inside this type json object we have two properties name and users and in which user is another object, so we will get users object from type object
JSONObject usr = jsonobj.getJSONObject("users");
Iterator<String> keys = usr.keys();
while(keys.hasNext()) {
String key = keys.next();
if (jsonObject.get(key) instanceof JSONObject) {
//print here
}
}
// String n1 = usr.getString("19x1");
// String n2 = usr.getString("19x5");
// String n3 = usr.getString("19x6");
//and So on......
Create XML for Spinner Android
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Spinner
android:id="#+id/spinner"
android:layout_width="149dp"
android:layout_height="40dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.498" />
And the MainActivity code is
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemSelectedListener {
String[] names = { n1,n2,n3};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);
//Creating the ArrayAdapter instance having the list
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,country);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}
//Performing action onItemSelected and onNothing selected
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
Toast.makeText(getApplicationContext(),names[position] , Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
String response = "{\n" +
" \"name\": \"assigned_user_id\",\n" +
" \"label\": \"Assigned To\",\n" +
" \"mandatory\": true,\n" +
" \"type\": {\n" +
" \"name\": \"owner\",\n" +
" \"users\": {\n" +
" \"19x1\": \"Admin Administrator\",\n" +
" \"19x5\": \"Ganeshprasad S\",\n" +
" \"19x6\": \"Balaji RR\",\n" +
" \"19x7\": \"Kiran Thadimarri\",\n" +
" \"19x8\": \"Sridhar Balakrishnan\",\n" +
" \"19x9\": \"Shilpa MK\",\n" +
" \"19x10\": \"Velmurugan N\",\n" +
" \"19x11\": \"Aamir Khanna\",\n" +
" \"19x12\": \"Jamir Abbas Pinjari\",\n" +
" \"19x13\": \"Syed Shadab Ashraf\",\n" +
" \"19x14\": \"Shahul Hameed\",\n" +
" \"19x15\": \"Manjula C\",\n" +
" \"19x16\": \"Keerthi Vasan L\",\n" +
" \"19x17\": \"Lochan Jyoti Borgohain\",\n" +
" \"19x18\": \"Rajkumar Sanatomba Singh\",\n" +
" \"19x19\": \"Krishna Pandey\",\n" +
" \"19x20\": \"Nabajit Pathak\",\n" +
" \"19x21\": \"Manoranjan Ningthoujam\",\n" +
" \"19x22\": \"Pravin Karbhari Ahire\",\n" +
" \"19x23\": \"Pratap Kumar Choudhary\"\n" +
" }\n" +
" }\n" +
"}";
This the data class
public class User {
private String id;
private String name;
public User(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
#Override
public String toString() {
return name;
}
#Override
public boolean equals(Object obj) {
if(obj instanceof User){
User user = (User )obj;
if(user.getName().equals(name) && user.getId()==id ) return true;
}
return false;
}
}
UserArrayList
This is how you can get the data
ArrayList<User> userList = new ArrayList<>();
try {
JSONObject jsonobj = new JSONObject(response);
JSONObject type = jsonobj.getJSONObject("type");
JSONObject usr = type.getJSONObject("users");
Iterator<String> keys = usr.keys();
while(keys.hasNext()) {
String key = keys.next();
String value = usr.getString(key);
User user = new User(key,value);
userList.add(user);
}
Log.e("value","value----"+userList);
} catch (JSONException e) {
e.printStackTrace();
}
This is the spinner Adapter
ArrayAdapter<User> adapter = new ArrayAdapter<User>(context, android.R.layout.simple_spinner_dropdown_item, userList );
spinneraccountManager.setAdapter(adapter);
spinneraccountManager.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
User user = (User) parent.getSelectedItem();
Toast.makeText(view.getContext(), "User ID: "+user.getId()+", User Name : "+user.getName(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
If I populate my listview with the primary key of my table I can get this primary key using getItemAtPosition and then it works fine.
The problem is that I don't want to use the primarykey to populate de listview, instead I want to use other fields of my table. Doing that, when I use the getItemAtPosition comand, because itsn't unic I can't use this to select my register.
I thought about using getItemIdAtPosition but I didn't reached any solution.
public void populateListView() {
//get the data and append to the list
Cursor data = db.getAllDataFillup(selectedID);
ArrayList<String> listData2 = new ArrayList<>();
while (data.moveToNext()) {
//listData2.add("FILLUP_ID: " + data.getString(0) + " FILLUP_VEHICLE_ID: " + data.getString(1));
//listData2.add(data.getString(7) + " " + data.getString(8) + " " + data.getString(2));
listData2.add(data.getString(3));
//listData2.add(data.getString(2));
}
//create the list adapter and set the adapter
ListAdapter adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listData2);
list_fillup.setAdapter(adapter2);
//set onItemClickListener to the listView
list_fillup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int fillupID = Integer.parseInt(adapterView.getItemAtPosition(i).toString());
long position = adapterView.getSelectedItemId();
//long a = list_fillup.get(codigoDoObjeto).getCodigoIdOuPKQualquer();
toastMessage("position: " + position);
//toastMessage("fillupPosition: " + fillupPosition);
//long fillupPosition = adapterView.getItemIdAtPosition(i);
Log.d(TAG, "onItemClick: You Clicked on " + fillupID);
Cursor data = db.getDataTableFillup(fillupID);//get the data associated with that fillupID
fillupID = -1;
while (data.moveToNext()) {
fillupID = data.getInt(0);
vehicleID = data.getInt(1);
fillupDate = data.getString(2);
odometer = data.getLong(3);
kmDriven = data.getLong(4);
liters = data.getLong(5);
consumption = data.getLong(6);
label = data.getString(7);
sequence = data.getInt(8);
}
if (fillupID > -1) {
Log.d(TAG, "onItemClick: The ID is: " + fillupID);
Intent screenVehicle = new Intent(Vehicle_painel.this, Fillup_edit.class);
screenVehicle.putExtra("fillupID", fillupID);
screenVehicle.putExtra("vehicleID", vehicleID);
screenVehicle.putExtra("vehicleName", selectedName);
screenVehicle.putExtra("date", fillupDate);
screenVehicle.putExtra("odometer", odometer);
screenVehicle.putExtra("kmDriven", kmDriven);
screenVehicle.putExtra("liters", liters);
screenVehicle.putExtra("consumption", consumption);
screenVehicle.putExtra("label", label);
screenVehicle.putExtra("sequence", sequence);
//toastMessage("fillupPosition: " + fillupPosition);
startActivity(screenVehicle);
} else {
toastMessage("fillupID = " + fillupID);
//db.deleteAllFillup(selectedID);
//toastMessage("No ID associated with that name hahaha");
}
The best thing to do would be to create a custom class to hold your data. That way you no longer just get a simple String value back from your adapter. Your ArrayList would be something like:
ArrayList<YourCustomClass> listData2 ...
Create a custom class "YourCustomClass" (Call it what ever you like). It could look like:
public class YourCustomClass {
private long itemId = 0;
private String itemName;
private String itemDescription;
public YourCustomClass(){
}
public void setItemId(long id){ this.itemId = id; }
public void setItemName(String itemName){ this.itemName = itemName; }
public void setItemDescription(String itemDescription){ this.itemDescription = itemDescription; }
public long getItemId() { return this.itemId; }
public String getItemName(){ return this.itemName; }
public String getItemDescription(){ return this.itemDescription; }
}
Now in your onItemClick method get the Id and the other data like this:
YourCustomClass data = (YourCustomClass) adapterView.getItemAtPosition(i);
long orderId = data.getItemId();
String name = data.getItemName();
You will need a custom adapter to populate your ListView with data.
You can also take a look at this answer. It shows how to change the background color of a ListView item, but also shows more detail of how to implement a custom adapter for your ListView.
How to set background color for each item listview depanding on variable value
I am new to android programming so apologies for any misuse of technical jargon. I have a spinner which has a text value of league_name and an id of id from the leagues SQLite table.
Example of leagues table design
id | league_name
-----------------
1 | Northern Premier Division
2 | Southern League 1
3 | Northern Division 2
I also have a teams table storing information on a team and a lookup table joining the id's of the teams and leagues table called teams_vs_leagues. So the selected value of this spinner gets inserted into the league_id column in the teams_vs_leagues table. I have an edit page to edit an individual teams record, which includes selecting a league from the spinner. However it always defaults to first available id in this case 1. Although, I want the initial value of the spinner to be the selected league_id in the teams_vs_leagues which corresponds to the team_id you are currently viewing. So if the selected team_id had a league_id of 3 I want the initial value of the spinner to be Northern Division 2.
UpdateTeam Class
public class UpdateTeam extends AppCompatActivity {
ArrayList < Team > imageArry = new ArrayList < Team > ();
TeamUpdateAdapter adapter;
Button updateButton;
DatabaseHelper myDb;
EditText teamNameEdit;
ImageView teamImage;
Spinner league; //Create Spinner Variables to cast in OnCreate method
ArrayList < String > leagues = new ArrayList < String > (); //Create Array List to bind to Spinner
ArrayAdapter < String > arrayAdapter; //Declare Array Adapter
long leagueId; //Declare global long for league_id
long id; //Declare global long for team_id
String picturePath = ""; //Create String variable for image path to be stored in db table
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_team);
myDb = new DatabaseHelper(this);
updateButton = (Button) findViewById(R.id.btnUpdate);
//Call Spinner Variable and cast spinner id reference
league = (Spinner) findViewById(R.id.edit_league_id);
//Call Array Adapter to Bind Array list data to Spinner
arrayAdapter = new ArrayAdapter < String > (this, android.R.layout.simple_list_item_1, leagues);
//get selected teams values from intent
id = getIntent().getLongExtra("TEAM", 0 l);
final String editTeamName = getIntent().getStringExtra("TEAM_NAME");
picturePath = getIntent().getStringExtra("IMAGE");
leagueId = getIntent().getLongExtra("LEAGUE_ID", 01);
//Toast.makeText(getBaseContext(), "Leagueid = " + leagueId, Toast.LENGTH_LONG).show();
teamNameEdit = (EditText) findViewById(R.id.eTeamName);
teamNameEdit.setText(editTeamName, TextView.BufferType.EDITABLE);
// Reading all teams from database
final List < Team > team = myDb.getTeam((int) id);
for (Team tm: team) {
String log = "ID:" + tm.getId() + " Team Name: " + tm.getTeamName() + " ,Image: " + tm.getPath() + " ,Points: " + tm.getPoints() + " ,League Name: " + tm.getLeagueName() + " ,League ID: " + tm.getLeagueId();
// Writing teams to log
Log.d("Result: ", log);
//add teams data in arrayList
imageArry.add(tm);
}
adapter = new TeamUpdateAdapter(this, R.layout.update_team,
imageArry);
ListView dataList = (ListView) findViewById(R.id.main_list_view);
dataList.setAdapter(adapter);
//call loadSpinnerData method
loadSpinnerData();
//call updateTeam
updateTeam();
//call selectLeague
selectLeague();
}
private void loadSpinnerData() {
// Spinner Drop down elements
List < Leagues > leagueList = myDb.getAllLeagues();
// Creating adapter for spinner
ArrayAdapter < Leagues > adapter = new ArrayAdapter < Leagues > (this,
android.R.layout.simple_spinner_item, leagueList);
// Drop down layout style - list view with radio button
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
league.setAdapter(adapter);
}
public void selectLeague() {
//set onItemSelected Listener for spinner
league.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView < ? > parent, View view, int position, long id) {
//get selected league id
leagueId = Integer.parseInt(String.valueOf(((Leagues) league.getSelectedItem()).getId()));
}
#Override
public void onNothingSelected(AdapterView < ? > parent) {
}
});
}
//Create addTeam method to add new team to db
public void updateTeam() {
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (myDb.updateTeam(
id,
teamNameEdit.getText().toString(),
picturePath,
leagueId)) {
Toast.makeText(getBaseContext(), "Update successful.", Toast.LENGTH_LONG).show();
Intent intent =
new Intent(UpdateTeam.this, DisplayTeam.class);
startActivity(intent);
} else
Toast.makeText(getBaseContext(), "Update failed.", Toast.LENGTH_LONG).show();
}
});
}
}
Leagues Class
public class Leagues {
//Declare Global String & int
private int id;
private String leagueName;
/*********** Set Methods ******************/
public Leagues(int id, String leagueName) {
this.id = id;
this.leagueName = leagueName;
}
public void setId(int id) {
this.id = id;
}
public void setLeagueName(String leagueName) {
this.leagueName = leagueName;
}
/*********** Get Methods ****************/
public int getId() {
return this.id;
}
public String getLeagueName() {
return this.leagueName;
}
//Provides string value to display in Spinner
#Override
public String toString() {
return leagueName;
}
}
getAllLeagues method
public List < Leagues > getAllLeagues() {
List < Leagues > labels = new ArrayList < Leagues > ();
// Select All Query
String selectQuery = "SELECT * FROM " + LEAGUES_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(new Leagues(cursor.getInt(0), cursor.getString(1)));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning labels
return labels;
}
If you need any further information, do not hesitate to leave a comment. Any help would be appreciated.
Provide the selected league object to getPosition() method of the array adapter
int index = arrayAdapter.getPosition(SELECTED_LEAGUE_ID);
league.setSelection(index);
I am trying to update my listview with notifyDataSetChanged() this method, but listview is not getting updated, if i press back button and go to previous activity and then again if i come in this activity then it is getting updated, i don't know why. I tried all possible solution but not getting proper solution. Please help Below is my code.
Here is a link which i tried
ListView not getting updated on calling notifyDataSetChanged()
notifyDataSetChanged() not working
notifyDataSetChanged Android ListView
notifyDataSetChanged not updating ListView
The event of notifyDataSetChanged()
public class Assignment extends Activity {
ListView mListView;
ImageView imageViewCrtAsnm;
String[] stg1;
List<String[]> names2 = null;
DataManipulator dataManipulator;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.assignment);
imageViewCrtAsnm = (ImageView) findViewById(R.id.createassignment);
mListView = (ListView) findViewById(R.id.displaydata);
imageViewCrtAsnm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Assignment.this,
Assignment_Create.class);
startActivity(intent);
}
});
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View item,
final int position, long id) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
Assignment.this);
alertDialogBuilder.setTitle("Delete Data");
alertDialogBuilder
.setMessage("Click yes to Delete Record!")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
String[] delete = names2.get(position);
String idString = delete[0];
long idLong = Long.valueOf(idString);
Log.d("Deleting...", idLong + "");
dataManipulator.delete(idLong);
names2.remove(position);
stg1 = new String[names2.size()];
int x = 0;
String stg;
for (String[] name : names2) {
stg = "Title : " + name[1] + "\n"
+ "Descr : " + name[2]
+ "\n" + "Day's Left : "
+ name[3];
stg1[x] = stg;
x++;
}
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
dataManipulator = new DataManipulator(this);
names2 = dataManipulator.selectAll();
stg1 = new String[names2.size()];
int x = 0;
String stg;
for (String[] name : names2) {
stg = "Title : " + name[1] + "\n" + "Descr : " + name[2] + "\n"
+ "Day's Left : " + name[3];
stg1[x] = stg;
x++;
}
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, stg1);
mListView.setAdapter(new ArrayAdapter<String>(this, R.layout.check,
stg1));
mListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
ArrayAdapter makes a copy of your items that you pass to it in the constructor and uses that internally.
ArrayAdapter Source
So simply manipulating your original array means nothing to the adapter. You are notifying it that the data has changed when it has not changed at all, it still holds the original list you populated it with.
You need to either recreate the entire adpater again or use the clear, addAll, remove or insert methods to manipulate the data.
http://developer.android.com/reference/android/widget/ArrayAdapter.html
You are recreating your array when you remove data. Have you tried also recreating your adapter to use the new array?
I found solution for this.
Just use onResume method to call adapter class...
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
names2 = dataManipulator.selectAll();
stg1 = new String[names2.size()];
int x = 0;
String stg;
for (String[] name : names2) {
stg = "Title : " + name[1] + "\n" + "Descr : " + name[2] + "\n"
+ "Day's Left : " + name[3];
stg1[x] = stg;
x++;
}
adapter = new ArrayAdapter<String>(this, R.layout.assignment_custom,
stg1);
mListView.setAdapter(adapter);
mListView.setCacheColorHint(Color.TRANSPARENT);
mListView.setBackgroundResource(R.drawable.assignment_icon);
adapter.notifyDataSetChanged();
adapter.setNotifyOnChange(false);
mListView.invalidateViews();
}
Just call this part of code in onResume method and you are done. But anyway thanks to all who have helped me. i am posting this answer here so may be other's can take benefit and not waste time like i did.
I have a ArticlesAdapter which I am using to read remote JSON data. The adapter is working but I am struggling to get my ListView setonitemclicklister working.
What I am trying to accomplish is the ability to click on a ListItem and to get the Article data for the option clicked on.
I have functions like getName() in my Article class which I need to call in response to a ListItem click but I can't seem to find a way to accomplish it.
I am trying to do this in my AsyncTask class.
Using the following code:
protected void onPostExecute(JSONArray result) {
// TODO Auto-generated method stub
Log.i("CHECK", "RESULTS: " + result);
List<Article> articles = new ArrayList<Article>();
String title = null;
String nid = null;
try{
for(int i=0; i < data.length(); i++){
JSONObject dataObj = (JSONObject)data.get(i);
JSONObject record = dataObj.getJSONObject("node");
title = (record.getString("title"));
nid = (record.getString("nid"));
Log.i("FOUND", "title: " + title);
Log.i("FOUND", "nid: " + nid);
articles.add( new Article(title, "", Integer.parseInt(nid)) );
}
}catch(JSONException j){
Log.e("CHECK", "Attempting to read data returned from JSONReader: " + j.toString());
}
ListView articlesList = (ListView)findViewById(R.id.articlesList);
ArticleAdapter adapter = new ArticleAdapter(ArticlesActivity.this, R.layout.article_item, articles);
articlesList.setAdapter(adapter);
articlesList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "testing : ", Toast.LENGTH_LONG);
Log.i("CHECK", "AdapterView: " + parent);
Log.i("CHECK", "VIEW : " + view);
Log.i("CHECK", "POSITION : " + position);
Log.i("CHECK", "ID : " + id);
}
});
if(dialog.isShowing())
dialog.dismiss();
}
My problem is I am not sure how to get the setOnItemClickListener working.
I am able to print the arguments via the Log function:
Log.i("CHECK", "AdapterView: " + parent);
Log.i("CHECK", "VIEW : " + view);
Log.i("CHECK", "POSITION : " + position);
Log.i("CHECK", "ID : " + id);
...but I get errors when I try casting any of the arguments into an Article object so I can call it's getName() function etc.
Your AsyncTask appears to be nested in your Activity, if it isn't simply pass articles to your Activity, then use:
articlesList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Article article = articles.get(position);
// Do something with article
}
});
An architectural change you would want to do is pull your ListView, Adapter, and OnItemClickListener initialization out of the AsyncTask and only update articles as well as notify the Adapter in the onPostExecute callback.