json listview delete not working android studio - android

I am loading some json into a list view and want to delete items from the list on click and for the item to be deleted from the json. The delete functionality seems to be working. The method delete is called, the items are removed on click and debugging shows the item being removed. However after going to another activity and viewing the list again, the deleted items come back. what am i doing wrong? This is my class:
public class edit extends AppCompatActivity
{
public ListView pizzaList;
ListView addicList;
ArrayAdapter<String> arrayAdapter;
String appreciations;
String currentPizza;
ArrayList<String> list = new ArrayList<String>();
private String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_activity);
pizzaList = (ListView) findViewById(R.id.pizzas);
registerForContextMenu(pizzaList);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
pizzaList.setAdapter(arrayAdapter);
pizzaList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
delete(view,position);
arrayAdapter.notifyDataSetChanged();
}
});
try {
FileManager fileManager = new FileManager();
String str = fileManager.ReadFile(this);
if (str != null) {
JSONArray jarray = new JSONArray(str);
String outputText = "";
for (int i = 0; i < jarray.length(); i++) {
JSONObject jsonObject = jarray.getJSONObject(i);
String pizzaName = jsonObject.getString("name");
int price = jsonObject.getInt("price");
outputText = outputText + " " + pizzaName + " " + " $" + price + "\n";
appreciations = outputText;
list.add(appreciations);
arrayAdapter.notifyDataSetChanged();
outputText = "";
}
} else {
Toast to = Toast.makeText(getApplicationContext(), "No saved Pizzas", Toast.LENGTH_LONG);
to.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void delete(View view, int pos)
{
try {
FileManager fileManager = new FileManager();
String str = fileManager.ReadFile(this);
if (str != null)
{
JSONArray jarray = new JSONArray(str);
JSONObject jsonObject = jarray.getJSONObject(pos);
jarray.remove(pos);
list.remove(pos);
arrayAdapter.notifyDataSetChanged();
JSONArray jsArray = new JSONArray(jarray);
arrayAdapter.notifyDataSetChanged();
} else {
Toast to = Toast.makeText(getApplicationContext(), "No saved Pizzas", Toast.LENGTH_LONG);
to.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

You would need to remove the item from the database, use asynchronous request such as volley or robospice for it. Then instead of making the request when coming back you would use the data stored on the cache the second time and only make the request again when data has been changed. You can create your cache logic in your application class to make it visible throughout your app.

Related

Volley does not work correctly when URL has UTF-8 on Android version less than 5

I use the volley library in my app, and I accidentally realized that my String URL for Android less than 5, the response from the server is empty, But in the higher version the answer is correct, So I checked My URL, Which is as follows:
string url ====> http://www.articler.ir/android_php/search.php?Method=rate&CAT=مهندسی%20عمران
Part of this has a character of UTF-8, Why this URL returns the correct response in higher versions of Android (5+). But the response is empty in the lower versions(5-)?
Please help me, thank You...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
final ListView listView = findViewById(R.id.test);
final CustomListAdapter adapter = new CustomListAdapter(this, myList);
Intent intent = getIntent();
FirstURL = intent.getStringExtra("SearchURL");
SearchURL = FirstURL.replaceAll(" ", "%20");
Log.d("Search", "Search: " + SearchURL);
myList.removeAll(myList);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(SearchURL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Toast.makeText(TestActivity.this, "", Toast.LENGTH_SHORT).show();
Log.d("VolleyRes", "response: " + response);
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Model model = new Model();
model.setTitle(jsonObject.getString("title"));
model.setMainText(jsonObject.getString("mainText"));
model.setrate(jsonObject.getDouble("rate"));
model.setYear(jsonObject.getInt("year"));
model.setConfName(jsonObject.getString("confName"));
model.setProductId(jsonObject.getInt("productId"));
model.setCountView(jsonObject.getInt("countView"));
model.setPdfURL(jsonObject.getString("pdfURL"));
// authors is json array
authors = new ArrayList<String>();
JSONArray authorArray = jsonObject.getJSONArray("authors");
for (int j = 0; j < authorArray.length(); j++) {
if (!authors.contains(authorArray.getString(j)) && !authorArray.isNull(j)) {
authors.add((String) authorArray.get(j));
}
}
model.setAuthor(authors);
// Keywords is json array
keywords = new ArrayList<String>();
JSONArray keywordArray = jsonObject.getJSONArray("Keywords");
for (int k = 0; k < keywordArray.length(); k++) {
if (!keywords.contains(keywordArray.getString(k)) && !keywordArray.isNull(k)) {
keywords.add((String) keywordArray.get(k));
}
}
model.setKeywords(keywords);
myList.add(model);
} catch (JSONException e) {
e.printStackTrace();
}
}
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("VolleyErr", "ErrorMassage: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int year = myList.get(position).getYear();
int productId = myList.get(position).getProductId();
int countView = myList.get(position).getCountView();
double rate = myList.get(position).getrate();
String title = myList.get(position).getTitle();
String mainText = myList.get(position).getMainText();
String confName = myList.get(position).getConfName();
ArrayList authors = myList.get(position).getAuthor();
ArrayList keywords = myList.get(position).getKeywords();
String pdfURL = myList.get(position).getPdfURL();
SharedPreferences prefs = PreferenceManager.
getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("productId", productId); //InputString: from the EditText
editor.putInt("countView", countView);
editor.putFloat("rate", (float) rate);
editor.putString("pdfURL",pdfURL);
editor.putString("title",title);
editor.putString("mainText",mainText);
editor.putString("confName",confName);
editor.putString("authors", String.valueOf(authors));
editor.putString("keywords", String.valueOf(keywords));
editor.putInt("year", year);
editor.commit();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getApplicationContext(),DetailActivity.class);
startActivity(intent);
// finish();
}
}, 1500);
}
});
}
}
After a lot of searches, I realized that URL with Persian fonts on Android less than 5 is not supported. So I need to change the string by encoding it so I used the method below to change it.
//this is initial string url ====> http://www.articler.ir/android_php/search.php?Method=rate&CAT=مهندسی%20عمران
String MyKey = مهندسی عمران;
final String EncodeKey= URLEncoder.encode(MyKey , "UTF-8");
String EncodeURL = " http://www.articler.ir/android_php/search.php?Method=rate&CAT= " + EncodeKey;
after changing this part, my response is correct, like 5+ version;

List view Not Displaying Data

so recently i had an issue that i could not get more than one record to display from a online database in my android app. I was using text view but was advised to utilize a list view. With the help of some kind people on here i have been pointed in the right direction how ever i am still having trouble as the list view does not display anything. I will attach the code below which i have annotated for this post.
For reference i am utilising volley and php, when accessing the data through the url, example: http://example.url/data.php/$id=1
public class GetExerciseList extends AppCompatActivity implements View.OnClickListener {
private EditText editTextId;
private Button buttonGet;
private TextView textViewResult;
ListView listView ;
ArrayAdapter adapter;
private ArrayList<String> dataList = new ArrayList<>();
private ProgressDialog loading;
INITIALIZING VIEWS
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_getexerciselist);
editTextId = (EditText) findViewById(R.id.editTextId);
buttonGet = (Button) findViewById(R.id.buttonGet);
textViewResult = (TextView) findViewById(R.id.textViewResult);
ListView listView = (ListView) findViewById(R.id.list);
adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, dataList);
listView.setAdapter(adapter);
buttonGet.setOnClickListener(this);
}
DECLARING ADAPTERS AND VIEWS
private void getData() {
String id = editTextId.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL+editTextId.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) { Toast.makeText(GetExerciseList.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
FETCHING DATA BASED ON MATCHING ID
private void showJSON(String response){
String musclegroup="";
String exercise="";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData;
for(int i = 0; i<result.length(); i++) {
collegeData = result.getJSONObject(i);
musclegroup = collegeData.getString(Config.KEY_MUSCLEGROUP);
exercise = collegeData.getString(Config.KEY_EXERCISE);
adapter.notifyDataSetChanged();
dataList.add(musclegroup + " " + exercise + " ");
}
FOR LOOP TO LOOP THROUGH JSON DATA, AND ADD ALL RECORDS TO THE DATALIST
} catch (JSONException e) {
e.printStackTrace();
}
EXCEPTION CATCHER
textViewResult.setText("Target Muscle:\t" + musclegroup + "\nLift:\t" + exercise);
// this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, dataList));
ListView lv = (ListView)findViewById(R.id.list);
lv.setAdapter(adapter);
ArrayAdapter<String> adapter =new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, dataList);
}
TEXTVIEW LEFT IN JUST TO CHECK DATA. LIST VIEW CURRENTLY HAS NO OUTPUT
LISTVIEW ADAPTER DECLARED AND SET, DATA SET AS "datalist"
#Override
public void onClick(View v) {
getData();
}
}
I have broken this down to make this easily readable, thank you everyone for the help as always it is very appreciated.
First of all, add the datas and notify the adatper.
private void showJSON(String response){
String musclegroup="";
String exercise="";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData;
for(int i = 0; i<result.length(); i++) {
collegeData = result.getJSONObject(i);
musclegroup = collegeData.getString(Config.KEY_MUSCLEGROUP);
exercise = collegeData.getString(Config.KEY_EXERCISE);
dataList.add(musclegroup + " " + exercise + " ");
adapter.notifyDataSetChanged();
}
Better solution is to create your adapter and set it to the ListView after the loop is finished instead to call adapter.notifyDataSetChanged(); every time in the loop until iterate your response.
private void showJSON(String response){
String musclegroup="";
String exercise="";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData;
for(int i = 0; i<result.length(); i++) {
collegeData = result.getJSONObject(i);
musclegroup = collegeData.getString(Config.KEY_MUSCLEGROUP);
exercise = collegeData.getString(Config.KEY_EXERCISE);
dataList.add(musclegroup + " " + exercise + " ");
}
adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, dataList);
listView.setAdapter(adapter);
}

OnPostExecute item to ListView

Here is OnPostExecute That retuns Listitem [name1,name2,name3]:
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String result = json.getString(KEY_SUCCESS);
if (Integer.parseInt(result) == 1) {
pDialog.setMessage("Loading View");
pDialog.setTitle("Getting Friends");
//JSONArray root = new JSONArray(json);
JSONArray friend = json.getJSONArray("users");
List<String> item = new ArrayList<String>();
for (int i = 0; i < friend.length(); i++) {
JSONObject att = (JSONObject) friend.getJSONObject(i);
String res = att.getString("username");
item.add(res);
}
SharedPreferences FriendList = getSharedPreferences("FriendList", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = FriendList.edit();
edit.putString("KEY_FRIENDS", item.toString());
edit.commit();
} else {
pDialog.dismiss();
}
}else {
pDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
pDialog.dismiss();
}
I want it In List View but im stucked, because i cant use ListAdapter in OnPostExecute.
public class FriendList extends ListActivity { ...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_friend_list);
// listt = (TextView) findViewById(R.id.testyL);
// list = (TextView) findViewById(R.id.textView4);
// list = (ListView) findViewById(R.id.label);
try {
new GetFriends().execute();
}catch (Exception e) {
e.printStackTrace() ;
Log.e("ERR ", "AsyncTASK" + e.toString());
}
SharedPreferences FriendList = getSharedPreferences("FriendList", Context.MODE_PRIVATE);
String u = FriendList.getString("KEY_FRIENDS", "0");
I tried to put item to SharedPref but it seems i dont know how to properly retrevie it and conter to variable that can be used by Array/List Adapter.
Here is the problem :)
// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, item ));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), Logged.class);
// sending data to new activity
i.putExtra("friend", product);
startActivity(i);
}
});
}
Change GetFriends constructor add reference to FriendList object:
try {
new GetFriends(FriendList.this).execute();
}catch (Exception e) {
e.printStackTrace() ;
Log.e("ERR ", "AsyncTASK" + e.toString());
}
class:
public class GetFriends extends [...]{
private ListActivity mList;
public GetFriends(ListActivity list){
mList = list;
}
[...]
#Override
protected void onPostExecute(JSONObject json) {
//set Adapter to list
mList.
}
}

Android populate spinner with string array

Below I have attached my code for trying to add my string array, names, to the spinner as the options. As of now, I am not getting anything populating the array, and I am really not sure what I'm doing wrong. I have looked over other similar questions on this site, as well as using Google, and have come up empty. Can anyone give me some guidance? Thanks
public class RunesActivity extends Activity {
public static String page;
TextView textName;
Spinner spinner;
ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rune_activity);
GetRunes getRunes = new GetRunes();
getRunes.execute();
spinner = (Spinner) findViewById(R.id.rune_selector);
}
public void addListenerOnSpinnerSelection() {
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
((TextView) adapterView.getChildAt(0)).setTextColor(Color.parseColor("#C49246"));
Toast.makeText(adapterView.getContext(),
"Page Selected: " + adapterView.getItemAtPosition(i).toString(),
Toast.LENGTH_SHORT).show();
page = adapterView.getItemAtPosition(i).toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
class GetRunes extends AsyncTask<String, String, JSONObject> {
private String api_key="d96236d2-6ee3-4cfd-afa7-f41bdbc11128";
String region = MainActivity.region.toLowerCase();
String id = StatsActivity.sumID;
String encodedKey = null;
String encodedRegion = null;
String encodedId = null;
String url = null;
// JSON Node Names
String TAG_NAME = "name";
String TAG_CURRENT = "current";
String TAG_SLOTS = "slots";
String TAG_RUNEID = "runeId";
String TAG_RUNESLOTID = "runeSlotId";
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
// Assign views
textName = (TextView) findViewById(R.id.name);
// Encode URL variables
encodedId = URLEncoder.encode(id, "UTF-8");
encodedKey = URLEncoder.encode(api_key, "UTF-8");
encodedRegion = URLEncoder.encode(region, "UTF-8");
url = "http://prod.api.pvp.net/api/lol/" + region + "/v1.4/summoner/" + id + "/runes?api_key=" + api_key;
Log.i("..........", url);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
protected JSONObject doInBackground(String... arg0) {
JSONParser jParser = new JSONParser();
// Get JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
Log.i("............", "" + json);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
// Get JSON Object
JSONObject runes = json.getJSONObject(encodedId);
// Get JSON Array node
JSONArray rune = runes.getJSONArray("pages");
// Loop through pages, page names stored in string array
String[] name = new String[rune.length()];
String curr;
ArrayList<String> runePageNames = new ArrayList<String>();
for(int i = 0; i < rune.length(); i++) {
JSONObject c = rune.getJSONObject(i);
name[i] = c.getString(TAG_NAME);
curr = c.getString(TAG_CURRENT);
if(curr.equals("true"))
name[i] = name[i] + " [Active]";
runePageNames.add(name[i]);
Log.i(".........", name[i]);
}
adapter = new ArrayAdapter(RunesActivity.this,
android.R.layout.simple_spinner_dropdown_item,
runePageNames);
addListenerOnSpinnerSelection();
// Set TextView
textName.setText(name[0]);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Try this..
before calling addListenerOnSpinnerSelection(); method set adapter for that spinner.
adapter = new ArrayAdapter(RunesActivity.this,
android.R.layout.simple_spinner_dropdown_item,
runePageNames);
spinner.setAdapter(adapter );
addListenerOnSpinnerSelection();

Having trouble adding string array to spinner entries

What I'd like to accomplish is the String array names[] be what you see in the spinner, but I cannot seem to figure out how to do this. I have tried looking off of other similar questions, but everything I try results in a crash in my app, saying that it is unable to instantiate the activity. Below, I have included the onPostExecute, where I am generating the string array, and also my addListenerOnSpinnerSelection() method. Any guidance would be great.
protected void onPostExecute(JSONObject json) {
try {
// Get JSON Object
JSONObject runes = json.getJSONObject(encodedId);
// Get JSON Array node
JSONArray rune = runes.getJSONArray("pages");
// Loop through pages, page names stored in string array
String[] name = new String[rune.length()];
String curr;
ArrayList<String> runePageNames = new ArrayList<String>();
for(int i = 0; i < rune.length(); i++) {
JSONObject c = rune.getJSONObject(i);
name[i] = c.getString(TAG_NAME);
curr = c.getString(TAG_CURRENT);
if(curr.equals("true"))
name[i] = name[i] + " [Active]";
runePageNames.add(name[i]);
Log.i(".........", name[i]);
}
adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item,
runePageNames);
addListenerOnSpinnerSelection();
// Set TextView
textName.setText(name[0]);
} catch (JSONException e) {
e.printStackTrace();
}
public void addListenerOnSpinnerSelection() {
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
((TextView) adapterView.getChildAt(0)).setTextColor(Color.parseColor("#C49246"));
Toast.makeText(adapterView.getContext(),
"Page Selected: " + adapterView.getItemAtPosition(i).toString(),
Toast.LENGTH_SHORT).show();
page = adapterView.getItemAtPosition(i).toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}

Categories

Resources