Change content of listview on button click(on same screen) - android

So In my MainActivity There are 3 rooms(coming from server).when i click on them popup is open.This popup will having shown the list of roomId(clicked on listview item).This works fine.
Now I need like this.In popup on click of next button next roomId with api to get its module is call and update the listview.
How i do this?
Problem is:-whenever going to do always it open with new popup.
As shown in picture I need to change the content of listview on toolbar's right arrow button.
My listview is in popup.so when i change content of listview this another new popup open for new list.
This is my 1st listview(where I load all images)
modules_list.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0,
android.view.View arg1, int arg2, long arg3) {
editor.putInt("response_position",arg2).commit();
editor.putString("roomid",response.getRooms()[arg2+1].getRooms_id().getRoomId()).commit();
String serverURL = "http://dashboard.droidhomes.in/api/module?room_id=" + response.getRooms()[arg2].getRooms_id().getRoomId();
// Use AsyncTask execute Method To Prevent ANR11 Problem
new GetallModules().execute(serverURL);
}
});
GetAllmodules class to get all modules and switches of Room:-
private class GetallModules extends AsyncTask<String, Void, Void> {
// Required initialization
// private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(
MainActivity.this);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
Dialog.setMessage("Please wait..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;
try {
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
editor = pref.edit();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String auth_token = pref.getString("auth_token", "");
conn.setRequestProperty("Authorization", auth_token);
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception ex) {
Error = ex.getMessage();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
/*****************************************************/
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
// Content=Content.replaceAll("<string>","");
// Content=Content.replaceAll("</string>", "");
Dialog.dismiss();
if (Error != null) {
Toast toast = Toast.makeText(getApplicationContext(),
"Bad request", Toast.LENGTH_LONG);
toast.show();
// uiUpdate.setText("Output : " + Error);
} else {
// Show Response Json On Screen (activity)
// uiUpdate.setText(Content);
/****************** Start Parse Response JSON Data *************/
// String OutputData = "";
// JSONObject jsonResponse;
Gson gson = new Gson();
final SearchResponse response = gson.fromJson(Content,
SearchResponse.class);
if (response.getStatus() == true) {
//response.getAuth_token()
if (response.getModule().length > 0) {
LayoutInflater li1 = LayoutInflater.from(MainActivity.this);
View promptsView = li1.inflate(R.layout.prompts_modulesdialog1, null);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(promptsView);
ListView list_modules = (ListView) promptsView.findViewById(R.id.lv_modules);
TextView tv_roomname = (TextView) promptsView.findViewById(R.id.tv_roomName);
ImageView iv_left=(ImageView)promptsView.findViewById(R.id.iv_left);
ImageView iv_right=(ImageView)promptsView.findViewById(R.id.iv_right);
ArrayList<String> switches = new ArrayList<String>();
iv_right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String room_id=pref.getString("roomid","");
String serverURL = "http://dashboard.droidhomes.in/api/module?room_id=" + room_id;
// Use AsyncTask execute Method To Prevent ANR11 Problem
new GetallModules().execute(serverURL);
}
});
for (int i = 0; i < response.getModule().length; i++) {
tv_roomname.setText(response.getModule()[i].getRoom_title());
for (int j = 0; j < response.getModule()[i].getSwitches().length; j++) {
if (response.getModule()[i].getModule_name().equals(response.getModule()[i].getSwitches()[j].getModule_name_switches())) {
switches.add(response.getModule()[i].getSwitches()[j].getSwitch_name());
}
}
}
ToggleButtonListAdapter t1=new ToggleButtonListAdapter(MainActivity.this, switches);
list_modules.setAdapter(t1);
t1.notifyDataSetChanged();
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else {
Toast.makeText(getApplicationContext(), "No module defined for this room!!!!!!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "status:-" + response.getStatus(), Toast.LENGTH_SHORT).show();
}
}
}
}
Same Scenario like this.
please help me!!

Related

Im able to populate spinner but cant access it

public void editarEstadoSala(final Sala sala) {
ArrayAdapter<Pelicula> adapter;
CambiarDatosSalaWorker cambiarDatosSalaWorker = new CambiarDatosSalaWorker(this);
cambiarDatosSalaWorker.execute();
List<Pelicula> listaPelicula=cambiarDatosSalaWorker.getLista();
LinearLayout layout = new LinearLayout(PortalAdmin.this);
layout.setOrientation(LinearLayout.VERTICAL);
//////
final AlertDialog.Builder builder = new AlertDialog.Builder(PortalAdmin.this);
builder.setTitle("Rellena los datos");
final EditText butacas = new EditText(PortalAdmin.this);
final EditText precio = new EditText(PortalAdmin.this);
final TextView pelicula = new TextView(PortalAdmin.this);
final Spinner spinner = new Spinner(PortalAdmin.this);
pelicula.setText("Pelicula seleccionada");
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
butacas.setInputType(InputType.TYPE_CLASS_NUMBER);
butacas.setHint("Numero butacas libres");
precio.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
precio.setHint("Precio entrada");
spinner.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
adapter = new ArrayAdapter<Pelicula>(PortalAdmin.this, android.R.layout.simple_spinner_item , listaPelicula);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String item = (String) parent.getItemAtPosition(position);
pelicula.setText(item);
} // to close the onItemSelected
public void onNothingSelected(AdapterView<?> parent)
{
Toast toast = Toast.makeText(PortalAdmin.this,
"nada",
Toast.LENGTH_SHORT);
toast.show();
}
});
layout.addView(butacas);
layout.addView(precio);
layout.addView(pelicula);
layout.addView(spinner);
builder.setView(layout);
// Set up the buttons
builder.setPositiveButton("Subir", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
I just cant make any progress here, the spinner is populated (List, comes from another class) but i cant do nothing with that data, Log.e doesnt show nothing so my code doesnt reach the spinner.setOnItemSelectedListener.
Sorry for my english guys, im learning code and english and im pretty bad at both.
Ok, the problem was here
CambiarDatosSalaWorker cambiarDatosSalaWorker = new CambiarDatosSalaWorker(this);
cambiarDatosSalaWorker.execute();
List<Pelicula> listaPelicula=cambiarDatosSalaWorker.getLista();
I was using my class "CambiarDatosSalaWorker" wrong and the code there was wrong too haha
Here is the class now,
public class CambiarDatosSalaWorker extends AsyncTask<Void, Void, List<Pelicula>> {
#Override
protected List<Pelicula> doInBackground(Void... params) {
String result = "";
String line = "";
List<Pelicula> lista = new ArrayList<>();
String datosPelicula = "here is the url where I get the info about the movies in my database";
try {
URL url = new URL(datosPelicula);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
result = "";
line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
int ndatos = result.split("-_-").length;
//String id, String nombre, String genero, String sinopsis, String url_imagen
for (int i = 0; i < ndatos; i++) {
Pelicula p = new Pelicula(result.split("-_-")[i].split("-")[0], result.split("-_-")[i].split("-")[1], result.split("-_-")[i].split("-")[2], result.split("-_-")[i].split("-")[3], result.split("-_-")[i].split("-")[4]);
System.out.println("id " + result.split("-_-")[i].split("-")[0]);
System.out.println("nombre " + result.split("-_-")[i].split("-")[1]);
System.out.println("genero " + result.split("-_-")[i].split("-")[2]);
System.out.println("sinopsis " + result.split("-_-")[i].split("-")[3]);
System.out.println("url " + result.split("-_-")[i].split("-")[4]);
lista.add(p);
}
return lista;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<Pelicula> peliculas) {
super.onPostExecute(peliculas);
}
}
Now it returns a List, I dont need a variable and method getList (wrong way to use the class).
And in my Activity I change to this...
//code
List<Pelicula> listaPelicula = null;
CambiarDatosSalaWorker cambiarDatosSalaWorker = new CambiarDatosSalaWorker();
try {
listaPelicula = cambiarDatosSalaWorker.execute().get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
//code
------ > listaPelicula = cambiarDatosSalaWorker.execute().get();
Now my spinner works just fine.

I am trying to parse a data from the following link

"http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings" - Link Which Iam Trying to parse
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button GetServerData = (Button) findViewById(R.id.GetServerData);
GetServerData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// WebServer Request URL
String serverURL = "http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
});
}
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView uiUpdate = (TextView) findViewById(R.id.textView2);
TextView jsonParsed = (TextView) findViewById(R.id.textView3);
int sizeData = 0;
EditText serverText = (EditText) findViewById(R.id.textView);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
try {
// Set Request parameter
data += "&" + URLEncoder.encode("data", "UTF-8") + "=" + serverText.getText();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception e) {
Error = e.getMessage();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
uiUpdate.setText("Output : " + Error);
}else
{
//Show Response Json Onscreen(Activity)
uiUpdate.setText( Content );
/****************** Start Parse Response JSON Data *************/
String OutputData = "";
try {
JSONObject jsono = new JSONObject(Content);
JSONObject mainObject = jsono.getJSONObject("data");
JSONArray jsonArray = mainObject.getJSONArray("standing");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
// get details2 JSONObject
String position = object.optString("position").toString();
String team = object.optString("team").toString();
OutputData += "Position: " + position + " "
+ "Team Name : " + team + " ";
}
/****************** End Parse Response JSON Data *************/
//Show Parsed Output on screen (activity)
jsonParsed.setText( OutputData );
}catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
**I am Creating a premier league application which shows all the datas needed for a premier league fan. As Iam new to this I am getting confused over json parsing and getting data from apis. So Can anyone Explain to me how to change my code or Some links which would help me correct it.
Above given is my java code of Main Activity.**
Thank You Everyone for Helping out. But I found my answer from the search over the internet. Here I used VOLLEY to call the link.
JSON PARSER CLASS
public class ParseJSON {
public static String[] position1;
public static String[] team;
public static String[] points;
public static final String JSON_ARRAY = "data";
public static final String CHILD_ARRAY = "standings";
public static final String KEY_ID = "position";
public static final String KEY_NAME = "team";
private JSONObject users = null;
private JSONArray user2=null;
private JSONObject user3=null;
private String json;
public ParseJSON(String json){
this.json = json;
}
protected void parseJSON() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONObject(JSON_ARRAY);
try {
user2=users.getJSONArray(CHILD_ARRAY);
position1 = new String[user2.length()];
team = new String[user2.length()];
points=new String[user2.length()];
for (int i = 0; i < user2.length(); i++) {
JSONObject jo = user2.getJSONObject(i);
try {
user3=jo.getJSONObject("overall");
points[i] = user3.getString("points");
System.out.println("Message me: "+points[i]);
}catch (Exception e)
{
e.printStackTrace();
}
position1[i] = jo.getString(KEY_ID);
team[i] = jo.getString(KEY_NAME);
System.out.println("Message me: "+position1[i]);
System.out.println("Message me: "+team[i]);
}
}catch (Exception e)
{
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Main Activity Class
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String JSON_URL="http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings";
private Button buttonGet;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonGet = (Button) findViewById(R.id.buttonGet);
buttonGet.setOnClickListener(this);
listView = (ListView) findViewById(R.id.listView);
}
#Override
public void onClick(View v) {
sendRequest();
}
private void sendRequest() {
final StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json){
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
CustomList cl = new CustomList(this, ParseJSON.position1,ParseJSON.team,ParseJSON.points);
listView.setAdapter(cl);
}
}
Custom Class for adding datas to list view
public class CustomList extends ArrayAdapter<String> {
private String[] position1;
private String[] team;
private String[] points;
private Activity context;
public CustomList(Activity context, String[] position1, String[] team, String[] points) {
super(context, R.layout.list_view_layout, position1);
this.context = context;
this.position1 = position1;
this.team = team;
this.points = points;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_view_layout, null, true);
TextView pos1 = (TextView) listViewItem.findViewById(R.id.position1);
TextView teamname = (TextView) listViewItem.findViewById(R.id.teamname);
TextView points1 = (TextView) listViewItem.findViewById(R.id.points);
pos1.setText("Position: "+position1[position]);
teamname.setText("Team: "+team[position]);
points1.setText("Points: "+points[position]);
return listViewItem;
}
}
Step 1 : Use Retroft + RxJava for Asynchronous API calls
Step 2 : Use Gson to Serialize and Deserialize.
Step 3 : Use json to POJO to have a Model Class
Simplify the code.

How to delete a list item from listview in android eclipse by clicking a button

I need to delete a list item from listview on clicking a delete button in android eclipse. The list values are populated from mysql database(JSON), so on deleting, I need to delete the same from database also.
Here is my main Activity; I need to delete a listitem from a listview on clicking a delete button on each item in the listview:
public class MainActivity extends Activity implements AsyncResponse2 {
private ProgressDialog dialog;
ListView l1;
//for getting count
TextView count;
private static final String TAG_COUNT = "cnt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //to hide title bar
setContentView(R.layout.activity_main);
l1=(ListView)findViewById(R.id.listView1);
/** Reference to the delete button of the layout main.xml */
Button btnDel = (Button) findViewById(R.id.deleteid);
initView();
//str for getting count
count=(TextView)findViewById(R.id.countid);
//to display count while loading(so outside buttonclick)
String key1 = "saasvaap123";
String signupid1 = "8";
String url2 = "http://gooffers.in/omowebservices/index.php/webservice/Public_User/saved_offers_list?";
//http://gooffers.in/omowebservices/index.php/webservice/Public_User/saved_offers_list?key=saasvaap123&signup_id=8
//put the below lines outside button onclick since we load the values into edittext when opening the app
CustomHttpClient2 task2 = new CustomHttpClient2();
task2.execute(url2,key1,signupid1);
task2.delegate = MainActivity.this;
//end
}
//str getting count
//str customhttp2
private class CustomHttpClient2 extends AsyncTask<String, String, String>{
public AsyncResponse2 delegate=null;
private String msg;
#Override
protected void onPostExecute(String result2) {
// TODO Auto-generated method stub
super.onPostExecute(result2);
delegate.processFinish2(result2);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
if(params == null) return null;
// get url from params
String url2 = params[0];
String key1 = params[1];
String signupid1 = params[2];
ArrayList<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key",key1));
postParameters.add(new BasicNameValuePair("signup_id",signupid1));
try {
// create http connection
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url2);
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// connect
HttpResponse response = client.execute(httppost);
// get response
HttpEntity entity = response.getEntity();
if(entity != null){
return EntityUtils.toString(entity);
}
else{
return "No string.";
}
}
catch(Exception e){
return "Network problem";
}
}
}
public void processFinish2 (String output2){
Toast.makeText(MainActivity.this,output2, Toast.LENGTH_SHORT).show();
try{
//str
JSONObject jsonResponse = new JSONObject(output2);
JSONArray aJson = jsonResponse.getJSONArray("gen_off");
// create apps list
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
//end
//str
String strCount = json.getString(TAG_COUNT);
count.setText(strCount);//setting name to original name text
//end
}
}catch (JSONException e) {
Toast.makeText(MainActivity.this,"Exception caught!", Toast.LENGTH_SHORT).show();
}
}
//end getting count
private void initView() {
// show progress dialog
// dialog = ProgressDialog.show(this, "", "Loading...");
String key="saasvaap123";
String signup_id="8";
String url = "http://gooffers.in/omowebservices/index.php/webservice/Public_User/saved_offers_list?";
FetchDataTask task = new FetchDataTask();
task.execute(url,key,signup_id);
}
public class FetchDataTask extends AsyncTask<String, Void, String>{
// private final FetchDataListener listener;
private String msg;
#Override
protected String doInBackground(String... params) {
if(params == null) return null;
// get url from params
String url = params[0];
String key1 = params[1];
String signupid1 = params[2];
ArrayList<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key",key1));
postParameters.add(new BasicNameValuePair("signup_id",signupid1));
//str
try {
// create http connection
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// connect
HttpResponse response = client.execute(httppost);
// get response
HttpEntity entity = response.getEntity();
if(entity != null){
return EntityUtils.toString(entity);
}
else{
return "No string.";
}
}
catch(Exception e){
return "Network problem";
}
}
//end
//
#Override
protected void onPostExecute(String sJson) {
try {
JSONObject jsonResponse = new JSONObject(sJson);
JSONArray aJson = jsonResponse.getJSONArray("gen_off");
Toast.makeText(MainActivity.this, aJson.toString(),Toast.LENGTH_SHORT).show();
// create apps list
List<SavedOffers> apps = new ArrayList<SavedOffers>();
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
SavedOffers app = new SavedOffers();
app.setTitle(json.getString("title"));
app.setOriginalRate(json.getString("price"));
app.setOfferRate(json.getString("off_price"));
app.setPercentage(json.getString("percent"));
app.setSavings(json.getString("savings"));
app.setUrl(json.getString("image"));
// add the app to apps list
apps.add(app);
}
SavedOffersAdapter adapter = new SavedOffersAdapter(MainActivity.this, apps);
// set the adapter to list
l1.setAdapter(adapter);
//for delete
// adapter.notifyDataSetChanged();
/** Defining a click event listener for the button "Delete" */
Button btnDel = (Button) findViewById(R.id.deleteid);
OnClickListener listenerDel = new OnClickListener() {
#Override
public void onClick(View v) {
/** Getting the checked items from the listview */
SparseBooleanArray checkedItemPositions = l1.getCheckedItemPositions();
int itemCount = l1.getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
adapter.remove(l1.get(i));
}
}
checkedItemPositions.clear();
adapter.notifyDataSetChanged();
}
};
/** Setting the event listener for the delete button */
btnDel.setOnClickListener(listenerDel);
/** Setting the adapter to the ListView */
l1.setAdapter(adapter); //end delete
//notify the activity that fetch data has been complete
// if(listener != null) listener.onFetchComplete(apps);
} catch (JSONException e) {
// msg = "Invalid response";
// if(listener != null) listener.onFetchFailure(msg);
// return;
}
}
/**
* This function will convert response stream into json string
* #param is respons string
* #return json string
* #throws IOException
*/
public String streamToString(final InputStream is) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e) {
throw e;
}
finally {
try {
is.close();
}
catch (IOException e) {
throw e;
}
}
return sb.toString();
}
}
}
// this is my adapter class , I think change is only needed in main activity
// , I need to delete a specific list item from listview on clicking the delete button
public class SavedOffersAdapter extends ArrayAdapter<SavedOffers>{
private List<SavedOffers> items;
Bitmap bitmap;
ImageView image;
public SavedOffersAdapter(Context context, List<SavedOffers> items) {
super(context, R.layout.app_custom_list, items);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
private class ViewHolder {
//TextView laptopTxt;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// ViewHolder holder;//added
View v = convertView;
if(v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.app_custom_list, null);
}
SavedOffers app = items.get(position);
if(app != null) {
TextView productName = (TextView)v.findViewById(R.id.nameid);
TextView originalRate = (TextView)v.findViewById(R.id.originalid);
originalRate.setPaintFlags(originalRate.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
TextView offerRate = (TextView)v.findViewById(R.id.offerid);
TextView percentage = (TextView)v.findViewById(R.id.discountid);
TextView savings = (TextView)v.findViewById(R.id.savingsid);
image =(ImageView)v.findViewById(R.id.prctimgid);
if(productName != null) productName.setText(app.getTitle());
if(originalRate != null) originalRate.setText(app.getOriginalRate());
if(offerRate != null) offerRate.setText(app. getOfferRate());
if(percentage != null) percentage.setText(app. getPercentage());
if(savings != null) savings.setText(app. getSavings());
if(image!=null){
new DownloadImageTask(image).execute(app.getUrl());
}
}
return v;
}
In your listviews adapter's getView method you link to the button on the layout your inflating and just attach a setOnClickListener... to the button and have it remove that item from your list or array that your adapter uses and then notifyDataHasChanged.
Delete that item from items in that position.
So 1. you want to delete the item from the ListView
2. you want to delete the item from the SQL DB.
The first one is very easy, but you kind of need to know the underlining adapter and how it serves data to your ListView. When you instantiate a BaseAdapter for the ListView you pass in a List or an array. This array will be the data your BaseAdapter serves to your ListView, each view in the listview will be showing an element from the array (done in getView()). If you dynamically delete one of those items, then adjust your array (or just use a List and it's .remove(), and finally notifyDataSetChanged(); your BaseAdapter will refresh your list without that View (or rather that View will be replaced with the new one). So for instance below I pass in a List<WeatherLocation> (WeatherLocation is a containing class that has weather stuff for a particular area (city, zipcode, degree"Biddeford", 04005, 72) to my BaseAdapter.
// Instantiate ListView
ListView lvLocations = (ListView) findViewById(R.id.lvLocations);
// Instantiate our BaseAdapter (pass in the List<WeatherLocation>)
WeatherLocationAdapter mWeatherLocationAdapter = new WeatherLocationAdapter(savedList, this, R.layout.view_weather_location);
lvLocations.setAdapter(mWeatherLocationAdapter);
This is an example of a regular ListView setting an Adapter to a custom BaseAdapter.
The BaseAdapter is so simple, that really the only method you care about (majorly) is the getView() method.
R.layout.view_weather_location is just a `LinearLayout` I made, it has 3 TextViews in it that I tie (show) my data with, by attaching data to those TextViews in the `getView()` method of the `BaseAdapter`. You would put a `Button there and tie it to what you want (to delete the data item)`.
public class WeatherLocationAdapter extends BaseAdapter{
private List <WeatherLocation> mLocations;
private Context mContext;
private int rowForLocationToInflate;
private LayoutInflater inflater;
public WeatherLocationAdapter(List<WeatherLocation> mLocations, Context mContext, int rowForLocationToInflate) {
this.mLocations = mLocations;
this.mContext = mContext;
this.rowForLocationToInflate = rowForLocationToInflate;
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//TODO just built up layout now must tie to it.
private void addLocation(WeatherLocation newLocation){
mLocations.add(newLocation);
//TODO maybe invalidate after adding new item.
}
#Override
public int getCount() {
return mLocations.size();
}
#Override
public WeatherLocation getItem(int position) {
return mLocations.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//TODO build a viewholder
View rowView = inflater.inflate(rowForLocationToInflate, parent, false);
TextView tvZipcode = (TextView) rowView.findViewById(R.id.tvZipCode);
TextView tvCity = (TextView) rowView.findViewById(R.id.tvCity);
TextView tvTemp = (TextView) rowView.findViewById(R.id.tvDegree);
tvZipcode.setText(mLocations.get(position).getZipcode());
tvCity.setText(mLocations.get(position).getCity());
tvTemp.setText(String.valueOf(mLocations.get(position).getTemperature()));
// If you had a Button in your LinearLayout you were attaching to you that you wanted to delete that view/item with, it would look something like this in my case.
Button bDel = (Button) row.findViewById(R.id.bDel);
bDel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mLocations.remove(position);
}
});
return rowView;
}
}
In the onClick you would also remove the item from the SQL db. I can show that too, but I feel you have some coding to do as it stands.

Executing Async tasks in fragments

I am attempting to execute an async task in a fragment after converting my activities into fragments. When I call my async task from the activity I have to pass 'this' with it in order to allow the async task to change text and things after it receives the information. I am a bit confused on how to do this all with fragments. Here is what I got so far:
I execute the asynck task with:
new GetYourTopTasteBeers(this).execute(url);
the code for the async task is:
public class GetYourTopTasteBeers extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public GetYourTopTasteBeers (Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting beers");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(R.id.topTasteBeers);
//make array list for beer
final List<ShortBeerInfo> tasteList = new ArrayList<ShortBeerInfo>();
for(int i = 0; i < jsonArray.length(); i++) {
String beer = jsonArray.getJSONObject(i).getString("beer");
String rate = jsonArray.getJSONObject(i).getString("rate");
String beerID = jsonArray.getJSONObject(i).getString("id");
String breweryID = jsonArray.getJSONObject(i).getString("breweryID");
int count = i + 1;
beer = count + ". " + beer;
//create object
ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID , breweryID);
//add to arraylist
tasteList.add(tempTaste);
//add items to listview
ShortBeerInfoAdapter adapter1 = new ShortBeerInfoAdapter(c ,R.layout.brewer_stats_listview, tasteList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
ShortBeerInfo o=(ShortBeerInfo)arg0.getItemAtPosition(arg2);
String tempID = o.id;
String tempBrewID = o.brewery;
Toast toast = Toast.makeText(c, tempID, Toast.LENGTH_SHORT);
toast.show();
//todo: change fragment to beer page
Intent myIntent = new Intent(c, BeerPage2.class);
myIntent.putExtra("id", tempID);
myIntent.putExtra("breweryID", tempBrewID);
c.startActivity(myIntent);
}
});
}
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
My problem is that I can not pass 'this' from a fragment...
Bonus Question:
Also as you can see I am not done converting my code for the fragments. I need to change this to load a fragment instead of change activity:
//todo: change fragment to beer page
Intent myIntent = new Intent(c, BeerPage2.class);
myIntent.putExtra("id", tempID);
myIntent.putExtra("breweryID", tempBrewID);
c.startActivity(myIntent);
HOw can I pass values between fragments like I am doing between activities in that above code?
Since Fragments don't admit this, you may call getActivity() instead which will provide the context you need to execute the AsyncTask.
Be careful, though, as running an AsyncTask within a Fragment may lead to return a result to the caller Activity that has already been destroyed at the time your AsyncTask concluded its process. It's necessary to take additional precautions, and always check whether the Fragment hasn't already been destroyed. This can be done using this.isAdded() in your Fragment.
A good practice is to cancel your AsyncTask in the onStop() and onPause() methods. That will make the onPostExecute() not execute code if the Fragment is not active anymore (getActivity() would return null).
You cannot pass this because in this situation this referrers to your fragment, which doesn't extend Context. But you need Context (your GetYourTopTasteBeers takes Context as a parameter):
public GetYourTopTasteBeers (Context context)
Instead, pass your Activity like so:
new GetYourTopTasteBeers(getActivity()).execute(url);

User Input to Url using Async Task

I'm currently using XMLPullParser to parse a page from a train station API. I'm doing this using Async task as to keep up with the newer versions of android.
Currently I have hardcoded the XML string into the class and the results display out in a listview.
However, I am having trouble appending the baseURL to add a user inputted query to the end of it. I had no trouble doing this before using Async Tasks using code along these lines:
public void StationDetails(){
//--- Search button ---
Button btnSearch = (Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//--- EditText View ---
EditText input = (EditText) findViewById(R.id.inputStation);
StringBuilder URL = new StringBuilder(baseURL);
URL.append(input);
String fullURL = URL.toString();
}
});
}
But I cannot relate this into the Async Method. I can't seem to find anything online and would really appreciate anyones help in this matter.
Here is the class with the hardcodes string:
public class Realtime extends Activity {
// Irish Rail Site URL
private static final String baseURL = "http://api.irishrail.ie/realtime/realtime.asmx/getStationDataByNameXML?StationDesc=Malahide";
// XML TAG Name
private static final String TAG_ITEM = "objStationData";
private static final String TAG_ORIGIN = "Origin";
private static final String TAG_DEST = "Destination";
private static final String TAG_SCHARR = "Scharrival";
private static final String TAG_EXPARR = "Exparrival";
private static final String TAG_DIRECT = "Direction";
private static final String TAG_STAT = "Status";
private static final String TAG_TRAINTYPE = "Traintype";
private RealtimeListviewAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stations_realtime_layout);
ListView listView = (ListView) findViewById(R.id.listview);
mAdapter = new RealtimeListviewAdapter(this);
// set adapter
listView.setAdapter(mAdapter);
// use AsyncTask to parse the URL data
ParseTask task = new ParseTask(this);
task.execute(baseURL);
// --- Register the list view for long press menu options
registerForContextMenu(listView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class ParseTask extends
AsyncTask<String, Void, ArrayList<StationDetails>> {
private ProgressDialog dialog;
public ParseTask(Context c) {
dialog = new ProgressDialog(c);
}
#Override
protected void onPreExecute() {
dialog.setMessage("Loading Station Info...");
dialog.show();
}
#Override
protected ArrayList<StationDetails> doInBackground(String... params) {
String strUrl = params[0];
HttpURLConnection httpConnection = null;
InputStream is = null;
try {
URL url = new URL(strUrl);
httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setConnectTimeout(10000);
httpConnection.setReadTimeout(10000);
httpConnection.connect();
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
is = httpConnection.getInputStream();
return parseNews(is);
}
} catch (Exception e) {
// TODO
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (httpConnection != null) {
httpConnection.disconnect();
httpConnection = null;
}
}
return null;
}
#Override
protected void onPostExecute(ArrayList<StationDetails> result) {
// set the result
mAdapter.setData(result);
// notify to refresh
mAdapter.notifyDataSetChanged();
// Close the progress dialog
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
private ArrayList<StationDetails> parseNews(InputStream in)
throws XmlPullParserException, IOException {
ArrayList<StationDetails> newsList = new ArrayList<StationDetails>();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser pullParser = factory.newPullParser();
pullParser.setInput(in, "UTF-8");
int eventType = pullParser.getEventType();
StationDetails item = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
String tagName;
if (eventType == XmlPullParser.START_TAG) {
tagName = pullParser.getName();
if (tagName.equals(TAG_ITEM)) {
item = new StationDetails();
} else if (tagName.equals(TAG_ORIGIN)) {
if (item != null) {
item.mOrigin = pullParser.nextText();
}
} else if (tagName.equals(TAG_DEST)) {
if (item != null) {
item.mDestination = pullParser.nextText();
}
} else if (tagName.equals(TAG_SCHARR)) {
if (item != null) {
item.mSchArrival = pullParser.nextText();
}
} else if (tagName.equals(TAG_EXPARR)) {
if (item != null) {
item.mExpArrival = pullParser.nextText();
}
} else if (tagName.equals(TAG_DIRECT)) {
if (item != null) {
item.mDirection = pullParser.nextText();
}
} else if (tagName.equals(TAG_STAT)) {
if (item != null) {
item.mStatus = pullParser.nextText();
}
}
} else if (eventType == XmlPullParser.END_TAG) {
tagName = pullParser.getName();
if (tagName.equals(TAG_ITEM)) {
newsList.add(item);
item = null;
}
}
eventType = pullParser.next();
}
return newsList;
}
EDIT UPDATE
Ok I put the stringbuilder for the fullURL in an onClickListener for a button. Now what I want is to execute the task when the button is clicked. I moved the parsetask task, .excute etc into this clickListener. However this gives me an error saying that the View.OnClickListener for realtime is undefined, i follow the quick fixes, but then when running the porject I get an error in the logcat saying cannot be cast to android.content.Context.
Heres a snippet of what the code looks like now after the quick fix
searchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Append user input to baseURL
StringBuilder URL = new StringBuilder(baseURL);
URL.append(userInput);
String fullURL = URL.toString();
// use AsyncTask to parse the URL data
ParseTask task = new ParseTask(this);
task.execute(fullURL);
}
});
public ParseTask(OnClickListener onClickListener) {
dialog = new ProgressDialog((Context) onClickListener);
}
and my logcat:
I still can't figure this out and anybodys help would be very welcom
Why won't you just send the full URL to the AsyncTask? Would look something like:
StringBuilder URL = new StringBuilder(baseURL);
URL.append(input);
String fullURL = URL.toString();// use AsyncTask to parse the URL data
ParseTask task = new ParseTask(this);
task.execute(fullURL);
OK problem solved.
What happened was I wasn't taking the userinput and appending it to the URL properly. Love how things are so simple some times. And I also used Realtime.this as Gleb suggested. Thanks for your help. Heres the code in the onClickListener that works...
searchBtn.setOnClickListener(new View.OnClickListener() {
private String userInput;
#Override
public void onClick(View v) {
ListView listView = (ListView) findViewById(R.id.listview);
mAdapter = new RealtimeListviewAdapter(Realtime.this);
//set adapter
listView.setAdapter(mAdapter);
StringBuilder URL = new StringBuilder(baseURL);
etStation = (EditText) findViewById(R.id.inputStation);
userInput = etStation.getText().toString();
URL.append(userInput);
String fullURL = URL.toString();
//use AsyncTask to parse the RSS data
ParseTask task = new ParseTask(Realtime.this);
task.execute(fullURL);
}
});

Categories

Resources