Send wrong values to the next activity in search [closed] - android

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i have problem with search, when user type something, listview will change, so the next activity will recive wrong values.
my code:
package com.example.finaltest;
import java.util.ArrayList;
import java.util.HashMap;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.text.TextWatcher;
import android.view.View;
public class Search extends ActionBarActivity {
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
// Listview Data
String products[] = getResources().getStringArray(R.array.search);
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.subject_name, products);
lv.setAdapter(adapter);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// When user changed the Text
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
Search.this.adapter.getFilter().filter(arg0);
}
});
// after click
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final String item = lv.getItemAtPosition(position).toString();
int total_number = 50;
for(int x = 1; x < total_number+1; x = x+1) {
String SubjectName = "subject_" + String.valueOf(x);
int resID = getResources().getIdentifier(SubjectName, "string", getPackageName());
String subject = getResources().getString(resID);
if(item.equals(subject)) {
String StringClass = "com.example.finaltest.Subject_" + String.valueOf(x);
Class<?> c = null;
if(StringClass != null) {
try {
c = Class.forName(StringClass);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Intent i = new Intent(getApplicationContext(), Show_Subjects.class);
String Subject_number = String.valueOf(position+1);
i.putExtra("subject_number", Subject_number);
startActivity(i);
}
}
}
});
}
#Override
public void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_settings:
Intent delIntent = new Intent(Search.this, Settings.class);
Search.this.startActivity(delIntent);
return true;
case R.id.action_favorites:
Intent delItemIntent = new Intent(Search.this, Favorites.class);
Search.this.startActivity(delItemIntent);
return true;
}
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
}
my string names are Subject_N , i want to send values of N to next activity(from item row number)
my language is persian ,also i have an other problem, search field only support english ! change language is Inactive

//outside the for loop
ArrayList<String> ArraySubject_number = new ArrayList<String>();
String Subject_number;
//initialize your arraylist inside the loop for each row
//use something like
//for each row
Subject_number = String.valueOf(position+1);
ArraySubject_number.add(Subject_number);
//outside for loop
Intent intent= new Intent(getApplicationContext(), Show_Subjects.class);
intent.putExtras("subject_number", ArraySubject_number);
then in your other activity use this code to access them
ArrayList<String> ArraySubject_number = (ArrayList<String>) getIntent().getSerializableExtra("subject_number");

Related

ListView item deletion not happening

The aim is that store the string in the normal listview and then user touch(click) it move to next page along with user selected item. Once user click "Reject button" in the Operation.java, the should go-off from the List.java activity. It is not happening. It shows "Unfortunately, System has stopped".
MainActivity.java
public static int loop_exute=0 // first page variable
Intent i = new Intent(getApplicationContext(), List.class);
startActivity(i);
List.java
import android.R.string;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class List extends ActionBarActivity implements OnItemClickListener {
private ListView mainListView ;
private ArrayAdapter<String> listAdapter ;
Button buttonSum;
static String[] name;
ArrayList<String> planetList = new ArrayList<String>();
int pos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
mainListView = (ListView) findViewById( R.id.mainListView );
Bundle extras = getIntent().getExtras();
if(MainActivity.loop_exute==0) // acces 1st page value because the string array value sholuld load only once in its life time
{
MainActivity.loop_exute=MainActivity.loop_exute+2;
name = new String[] { "AAA", "BBB", "CCC", "DDD"
};
planetList.addAll( Arrays.asList(name) );
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, planetList);
mainListView.setAdapter( listAdapter );
//mainListView.getChildAt(0).setBackgroundColor(Color.RED);
show();
}
else // second time call
{
Intent intent = getIntent();
if(intent.hasExtra("MESSAGE"))
{
Bundle bd = getIntent().getExtras();
if(!bd.getString("MESSAGE").equals(null))
{
String object=bd.getString("MESSAGE");
int pos=planetList.indexOf(object);
planetList.remove(pos);
listAdapter.notifyDataSetChanged(); //show();
}
}
}
}
public void show()
{
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
Intent i = new Intent(getApplicationContext(), Operation.class);
i.putExtra("Value2",name[pos]);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}
Operation.java
reject = (ImageButton) findViewById(R.id.imageButton2);
reject.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), List.class);
i.putExtra("MESSAGE",value1); //send the list item value what we select in previous activity
startActivity(i);
}
});
In the setOnClickListener under Operation.java, you are trying to start another activity. Instead, insert code to manually destroy the activity. You can also use the finish() method. Here's a link to know more about it:
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

multiple order entries in android application

I'm working on an order management system for android.
On the order page where the user submits an order, i want it to be able to allow the user to submit multiple orders, then take the user to a page where it displays all the orders made.
What method can i use to accomplish that?
This is the order activity page which is made up of 3 spinners and one textfield. This page takes the user to a ViewOrder page which displays what the user has selected. Instead of that i would like the user to submit multiple orders first, then see the display of all orders submitted. Any help is much appreciated.
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.androidhive.R;
public class OrderActivity extends Activity {
public Button btnOrder;
public EditText txtCrates;
public Spinner sp1, sp2, sp3;
public List<String> list;
public static String crates;
public static final String EXTRA_MESSAGE = "com.example.myspinner.msg1";
public static final String EXTRA_MESSAGE2 = "com.example.myspinner.msg2";
public static final String EXTRA_MESSAGE3 = "com.example.myspinner.msg3";
public static final String EXTRA_MESSAGE4 = "com.example.myspinner.MESSAGE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order);
sp1 = (Spinner) findViewById(R.id.spinner1);
sp2 = (Spinner) findViewById(R.id.spinner2);
sp3 = (Spinner) findViewById(R.id.spinner3);
btnOrder = (Button) findViewById(R.id.btnOrder);
txtCrates =(EditText) findViewById(R.id.crates);
list = new ArrayList<String> ();
list.add("CocaCola");
list.add("Sprite");
list.add("Fanta Orange");
list.add("Fanta Pineapple");
list.add("Fanta Blackcurrant");
list.add("Fanta Passion");
list.add("Krest");
list.add("Stoney");
list.add("Dasani");
list.add("Minute Maid Apple");
list.add("Minute Maid Mango");
list.add("Minute Maid Orange");
final String[] str1={"300ml","500ml","1 Litre","1.25 Litres","2 Litres"};
ArrayAdapter<String> adp1 = new ArrayAdapter<String>
(this, android.R.layout.simple_dropdown_item_1line, list);
ArrayAdapter<String> adp2 = new ArrayAdapter<String>
(this, android.R.layout.simple_dropdown_item_1line, str1);
ArrayAdapter<CharSequence> adp3 = ArrayAdapter.createFromResource
(this, R.array.str2, android.R.layout.simple_dropdown_item_1line);
sp1.setAdapter(adp1);
sp2.setAdapter(adp2);
sp3.setAdapter(adp3);
btnOrder.setOnClickListener(new View.OnClickListener() {
/** Called when the user clicks the Submit Order button */
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),ViewOrder.class);
String msg1=sp1.getSelectedItem().toString();
String msg2=sp2.getSelectedItem().toString();
String msg3=sp3.getSelectedItem().toString();
String message = txtCrates.getText().toString();
intent.putExtra(EXTRA_MESSAGE, msg1);
intent.putExtra(EXTRA_MESSAGE2, msg2);
intent.putExtra(EXTRA_MESSAGE3, msg3);
intent.putExtra(EXTRA_MESSAGE4, message);
startActivity(intent);
}
});
sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), list.get(arg2),
Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sp2.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), str1[arg2],
Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sp3.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String item = sp3.getSelectedItem().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
Once try as follows take an List for multiple orders
ArrayList<String> orders=new ArrayList<String>();
as class variable in activity
then store a complete order as string with some special character as divider like
String msg1=sp1.getSelectedItem().toString();
String msg2=sp2.getSelectedItem().toString();
String msg3=sp3.getSelectedItem().toString();
String message = txtCrates.getText().toString();
orders.add(msg1+","+msg2+","+msg3+","+message);
then for intent add as follows
intent.putStringArrayListExtra("orders", orders);
Hope this will helps you.

What is the correct way implement switch case statement in Android?

It didn't showing up any error. however when I run my application, there is no result appear from my listView. I think,the mistake is because of i didn't use the correct way doing switch case statement. here is my code.
QuickSearch.java
package com.example.awesome;
import java.io.IOException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.SQLException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class QuickSearch extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
//-------------------------------------------------------------------------
// Initiate database data
initiateDb();
//---------------------------------------------------------------------------
// Declaration of view
final Button qsfaculty, qscollege;
super.onCreate(savedInstanceState);
setContentView(R.layout.quick_search);
//---------------------------------------------------------------------------
// Get reference
qsfaculty = (Button) this.findViewById(R.id.button1);
qsfaculty.setOnClickListener(this);
qscollege = (Button) this.findViewById(R.id.button2);
qscollege.setOnClickListener(this);
}
public void onClick(View v) {
char ch = 0;
View qsfaculty = null;
View qscollege = null;
if(v == qsfaculty){
ch = 'a';
}
else if (v == qscollege)
{ch = 'b';}
Intent i = new Intent(this,SearchLocation.class);
i.putExtra("value",ch);
startActivity(i);
}
//---------------------------------------------------------------------------
// Initiate database data
public void initiateDb() {
DatabaseHandler myDbHandler = new DatabaseHandler(this);
try {
myDbHandler.createDataBase();
}
catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHandler.openDataBase();
}
catch(SQLException sqle) {
throw sqle;
}
Log.d("Initiate", "UKM Location Count: " + myDbHandler.getUkmLocationCount());
myDbHandler.close();
}
//------------------------------------------------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quick_search, menu);
return true;
}
}
SearchLocation.java
package com.example.awesome;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class SearchLocation extends ListActivity {
//------------------------------------------------------------------
// Declaration
public static UkmLocation selectedPOI = null;
final DatabaseHandler db = new DatabaseHandler(this);
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
final ArrayList<String> results = new ArrayList<String>();
final ArrayList<String> results_id = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_location);
final Intent c = new Intent(SearchLocation.this, LocationDetail.class);
//------------------------------------------------------------------
// Link editText to layout item
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
//------------------------------------------------------------------
// Reading Poi
Log.d("Reading", "Reading all Kategori ..");
int value = 0;
switch(value) {
case 'a' :
List<UkmLocation> faculty = db.getCategoryFaculty();
for(UkmLocation k : faculty) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
case 'b' :
List<UkmLocation> college = db.getCategoryCollege();
for(UkmLocation k : college) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
}
//------------------------------------------------------------------
// Set list arrayAdapter to adapter
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView1,results);
setListAdapter(adapter);
//------------------------------------------------------------------
// Set ListView from ListActivity
ListView lv = getListView();
lv.setTextFilterEnabled(true);
//------------------------------------------------------------------
// Set click event from listView
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
Log.d("test", "position:" + position);
Log.d("test", "actualname:" + db.getUkmLocationByName(adapter.getItem(position)).getName());
// String poiID = results_id.get(position);
String poiID = db.getUkmLocationByName(adapter.getItem(position)).getID();
setSelectedPoi(poiID);
startActivity(c);
}
});
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
public UkmLocation getSelectedPoi() {
return selectedPOI;
}
public void setSelectedPoi(String poiID) {
selectedPOI = db.getUkmLocation(poiID);
Log.d("test2", "_id:" + db.getUkmLocation(poiID).getID());
Log.d("test2", "Name:" + db.getUkmLocation(poiID).getName());
// Closing db
db.close();
}
}
i think,the if else statement inside QuickSearch.java is already correct. the problem at the switch case statement at SearchLocation.java
please help me solve this.
int value = 0;
switch(value) {
You are setting the value over which you switch to 0 so it is equivalent to doing switch(0) {...
Find out what that value is supposed to be and initialise it properly.
Also, value is of type int but your switch uses chars ('a', 'b'), so you need to either have value be a char and initialise it properly or have it be an int, initialise it properly and change your switch cases to use ints.
First you do int value = 0; so value is 0. So it is not 'a' nor 'b'.
You have to get the value from the intent as you put it in extras. i.putExtra("value",ch);
something like
char value;
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getIntgetChar("value");
}
here, i already solve my problem..
QuickSearch.java
public void onClick(View v) {
int ch = 0;
/*View qsfaculty = null;
View qscollege = null;*/
if(v == qsfaculty){
ch = '1';
}
else if (v == qscollege)
{ch = '2';}
Intent i = new Intent(this,SearchLocation.class);
i.putExtra("value",ch);
startActivity(i);
}
SearchLocation.java
Bundle extras = getIntent().getExtras();
int value = extras.getInt("value");
switch(value) {
case '1' :
List<UkmLocation> faculty = db.getCategoryFaculty();
for(UkmLocation k : faculty) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
case '2' :
List<UkmLocation> college = db.getCategoryCollege();
for(UkmLocation k : college) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
}

SherlockListActvity onItemClick not working

I'm working on an application and I've implemented sherlockListActvity to display list. But onItemClickListener is not working on this. I tried searching in internet and none of them worked for me. I did everything I found in the internet to solve this problem. Please help me on this. I'm newbie to android. The code goes like this.
NewsActivity.java
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.ministry.ensing119app.Contact;
import com.ministry.ensing119app.HomeScreen;
import com.ministry.ensing119app.R;
import com.ministry.ensing119app.bible.BibleActivity;
import com.ministry.ensing119app.donate.Donate;
import com.ministry.ensing119app.photos.GetPath;
import com.ministry.ensing119app.sermonnotes.Notes_list;
public class NewsActivity extends SherlockListActivity {
public static String url = "http://ensignweb.com/sandbox/app/comment11.php";
// JSON Node names
protected static final String TAG_PRODUCTS = "products";
protected static final String TAG_CID = "cid";
public static final String TAG_NAME = "name";
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
// contacts JSONArray
JSONArray products = null;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
actionBar = getSupportActionBar();
setContentView(R.layout.activity_news);
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
Log.d("if condition", "if condition is running");
new Message().execute(url);
// The service section
Intent intent = new Intent(this,UpdateService.class);
PendingIntent pIntent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30000, pIntent);
startService(new Intent(this, UpdateService.class));
} else {
Log.d("if condition", "else condition is running");
Toast.makeText(getApplicationContext(), "There is no internet or low. Please check", Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent(NewsActivity.this, HomeScreen.class);
startActivity(returnIntent);
}
ListView list = getListView();
list.setClickable(true);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
TextView clickedData = (TextView) ((TextView) arg1).getText();
Toast.makeText(getApplicationContext(),
clickedData.toString(), Toast.LENGTH_SHORT).show();
}
});
}
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.news, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case R.id.donate:
Intent newsIntent = new Intent(NewsActivity.this, Donate.class);
startActivity(newsIntent);
break;
case R.id.photos:
Intent photoIntent = new Intent(NewsActivity.this, GetPath.class);
startActivity(photoIntent);
break;
case R.id.notepad:
Intent notePadIntent = new Intent(NewsActivity.this, Notes_list.class);
startActivity(notePadIntent);
break;
case R.id.contact:
Intent contactIntent = new Intent(NewsActivity.this,Contact.class);
startActivity(contactIntent);
break;
case R.id.bible:
Intent BibleIntent = new Intent(NewsActivity.this, BibleActivity.class);
startActivity(BibleIntent);
break;
}
return super.onMenuItemSelected(featureId, item);
}
class Message extends AsyncTask<String, Integer, ArrayList<HashMap<String, String>> > {
ListView lv = (ListView) findViewById(android.R.id.list);
ProgressDialog progress = new ProgressDialog(NewsActivity.this);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... params) {
Log.d("doInBackgound","backgound is running");
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
Log.d("path_parsing", "before parsing");
try {
// Getting Array of Contacts
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Contacts
for(int i = products.length()-1; i >=0; i--){
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String cid = c.getString(TAG_CID).toString();
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CID, cid);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
mylist.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("path_parsing", "after parsing");
return mylist;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
if(progress.isShowing()){
progress.dismiss();
}
ListAdapter adapter = new SimpleAdapter(NewsActivity.this, result , R.layout.list_item,new String[] { TAG_NAME,}, new int[] {
R.id.name});
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
Log.d("postExecute","Postexecute is running");
lv.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Log.d("selected", String.valueOf(arg2).toString());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progress.setTitle("Progress");
progress.setMessage("Please have patience");
progress.show();
}
}
}
try this
public class NewsActivity extends SherlockListActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
ListView list = getListView();
list.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
Toast.makeText(this, "test click position: " + arg2, Toast.LENGTH_SHORT).show();
}
});
list.setAdapter(YOUR ADAPTER)
}
}
If you don't see a message, please, post your xml (activity_news.xml)

ListView not updated after database is changed

I'm really frustrated because of bad programming style, and inexperience in Android. Sorry to tell you guys that.
How the app works:
This is a todo app for my job training. There are 6 columns.
3 of these contain information about the todo and the other 3 contain a view detail, edit, and remove screen.
When the user clicks remove for some reason even after setting a notifyDataChange, my screen is not updated and the deleted row it's still displayed.
Any ideas of what is going on here? I've tried many solutions for about 3 hours now
The code is posted here sorry if its a bit tedious.
The whole class with the ListViews:
package com.DCWebMakers.Vairon;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class ManageAppointment extends Activity {
ListView rowLi, whenLi, postedLi, detailsLi, editLi, removeLi;
ArrayAdapter<String> whenAdapter, postedAdapter, detailsAdapter,
editAdapter, removeAdapter;
ArrayAdapter<Integer> rowAdapter;
final AppointmentInfo information = new AppointmentInfo(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
/*
* The ListViews created here are not the proper way to make ListViews.
* This is for testing purposes and will be updated for efficiency. The
* remove also doesn't work properly
*/
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_appointment);
initVariables();
try {
databaseManagement();
detailsLi.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> aV, View v, int pos,
long arg3) {
// TODO Auto-generated method stub
Intent openDetails = new Intent(
"com.DCWebMakers.Vairon.APPOINTMENTDETAILS");
openDetails.putExtra("position", pos);
startActivity(openDetails);
}
});
editLi.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> aV, View v, int pos,
long arg3) {
// TODO Auto-generated method stub
Intent openEdit = new Intent(
"com.DCWebMakers.Vairon.EDITAPPOINTMENT");
openEdit.putExtra("position", pos);
startActivity(openEdit);
notifyChangesToAdapters();
}
});
removeLi.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> aV, View v, int pos,
long arg3) {
// TODO Auto-generated method stub
databaseManagement();
information.open();
information.delete(pos);
information.close();
Dialog sucDeleted = new Dialog(ManageAppointment.this);
sucDeleted.setTitle("Sucesfully deleted");
TextView tvDintWorked = new TextView(ManageAppointment.this);
tvDintWorked.setText("The appointment at position:" + pos
+ " was sucesfully deleted");
sucDeleted.setContentView(tvDintWorked);
sucDeleted.show();
notifyChangesToAdapters();
}
});
} catch (Exception e) {
Dialog showError = new Dialog(this);
showError.setTitle("Error");
TextView tvDintWorked = new TextView(this);
String error = e.toString();
tvDintWorked.setText(error);
showError.setContentView(tvDintWorked);
showError.show();
}
}
public void initVariables() {
rowLi = (ListView) findViewById(R.id.rowList);
whenLi = (ListView) findViewById(R.id.whenList);
postedLi = (ListView) findViewById(R.id.postedList);
detailsLi = (ListView) findViewById(R.id.detailsList);
editLi = (ListView) findViewById(R.id.editList);
removeLi = (ListView) findViewById(R.id.removeList);
}
#Override
protected void onPause() { // TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
notifyChangesToAdapters();
}
private void notifyChangesToAdapters() {
// TODO Auto-generated method stub
rowAdapter.notifyDataSetChanged();
whenAdapter.notifyDataSetChanged();
postedAdapter.notifyDataSetChanged();
detailsAdapter.notifyDataSetChanged();
editAdapter.notifyDataSetChanged();
removeAdapter.notifyDataSetChanged();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent mainIntent = new Intent("com.DCWebMakers.Vairon.MAINMENU");
startActivity(mainIntent);
}
public void databaseManagement() {
information.open();
int primaryKey = information.getKeys();
String when[] = information.getWhen();
String posted[] = information.getPosted();
String details[] = new String[primaryKey];
Integer rowNumber[] = new Integer[primaryKey];
String edit[] = new String[primaryKey];
String delete[] = new String[primaryKey];
for (int set = 0; set < rowNumber.length; set++) {
rowNumber[set] = (set);
}
for (int set = 0; set < details.length; set++) {
details[set] = ("Details");
}
for (int set = 0; set < edit.length; set++) {
edit[set] = ("Edit");
}
for (int set = 0; set < delete.length; set++) {
delete[set] = ("Delete");
}
information.close();
rowAdapter = new ArrayAdapter<Integer>(ManageAppointment.this,
android.R.layout.simple_list_item_1, rowNumber);
whenAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, when);
postedAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, posted);
detailsAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, details);
editAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, edit);
removeAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, delete);
rowLi.setAdapter(rowAdapter);
whenLi.setAdapter(whenAdapter);
postedLi.setAdapter(postedAdapter);
detailsLi.setAdapter(detailsAdapter);
editLi.setAdapter(editAdapter);
removeLi.setAdapter(removeAdapter);
}
}
The delete method:
public void delete(int position) {
theDatabase.beginTransaction();
try {
theDatabase
.delete(DATABASE_TABLE, KEY_ROWID + "=" + position, null);
theDatabase.setTransactionSuccessful();
} catch (SQLiteException e) {
// TODO: handle exception
e.printStackTrace();
} finally {
theDatabase.endTransaction();
theDatabase.close();
}
}
before notifyDataSetChanged you need to remove the entry from the List
Did you see any exception when deleting from database. and you also need to delete pos entry from global list before notifying.

Categories

Resources