[Q] No idea how to load onChildClick in my ExpandableListView. - Java for Android App Development

I have an expandable list view with 2 parents and 3 children. I want to open a dialog based on each click. I can't find any examples showing you how to call something based on positions. At least not with the ExpandableListView tutorial I followed.
Code:
public class MainActivity extends Activity implements OnClickListener {
private LinkedHashMap<String, HeaderInfo> myDepartments = new LinkedHashMap<String, HeaderInfo>();
private ArrayList<HeaderInfo> deptList = new ArrayList<HeaderInfo>();
private MyListAdapter listAdapter;
private ExpandableListView myList;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Just add some data to start with
loadData();
// get reference to the ExpandableListView
myList = (ExpandableListView) findViewById(R.id.myList);
// create the adapter by passing your ArrayList data
listAdapter = new MyListAdapter(MainActivity.this, deptList);
// attach the adapter to the list
myList.setAdapter(listAdapter);
// listener for child row click
myList.setOnChildClickListener(myListItemClicked);
// listener for group heading click
myList.setOnGroupClickListener(myListGroupClicked);
}
// load some initial data into out list
private void loadData() {
addProduct("Parent One", "Child One");
addProduct("Parent One", "Child Two");
addProduct("Parent One", "Child Three");
addProduct("Parent Two", "Child One");
addProduct("Parent Two", "Child Two");
addProduct("Parent Two", "Child Three");
}
// our child listener
private OnChildClickListener myListItemClicked = new OnChildClickListener() {
[user=439709]@override[/user]
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// Create a switch that switches on the specific child position.
// get the group header
HeaderInfo headerInfo = deptList.get(groupPosition);
// get the child info
DetailInfo detailInfo = headerInfo.getProductList().get(
childPosition);
// display it or do something with it
// custom dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.cdialog);
// dialog.setTitle(R.id.titlebar);
dialog.setTitle(R.string.titlebar);
dialog.show();
return false;
}
};
// our group listener
private OnGroupClickListener myListGroupClicked = new OnGroupClickListener() {
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// get the group header HeaderInfo headerInfo =
deptList.get(groupPosition);
// display it or do something with it
return false;
}
};
I can get a custom dialog open if I click a child, but it's not set to any specific parent and child.
Any ideas?
EDIT ADD: Got it. Tried a switch/case like this and it worked. Finally! After two days of trying to understand it.:fingers-crossed:
Code:
switch(groupPosition) {
case 1:
switch (childPosition) {
case 0:
Intent protheanIntent = new Intent(Codex.this, CodexProthean.class);
Codex.this.startActivity(protheanIntent);
break;
case 1:
Intent rachniIntent = new Intent(Codex.this, CodexRachni.class);
Codex.this.startActivity(rachniIntent);
break;
}
case 2:
switch (childPosition) {
case 2:
Intent asariIntent = new Intent(Codex.this, CodexAsari.class);
Codex.this.startActivity(asariIntent);
break;
}
}

Related

widget SMS for android

Hello,
I'm trying to write code of a widget sms for android. But I have a problem of cursor, after lot of test on compiling I dircoverd that
Code:
Cursor c = context.getContentResolver().query(Uri.parse("content://sms/"), null, null ,null,null);
make an error and I don't no why. If somebody knows how use a cursor or have a better idea to view sms without cursor, I woold like share it with him!
thank's
try something like this
Code:
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(uriSms, null,null,null,null);
Thank's to you Draffodx, I such begin my widget, now it can put on screen the sms I want... but I can't change of SMS with th button I've created. I don't understand how make a button with the widget because it need to be an Activity for a button and I've made an AppWidget...
I trying to do like this:
Code:
public class MySMSwidget extends AppWidgetProvider implements View.OnClickListener {
private Button Bnext;
private int sms_id=0;
public class MyActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.widget_layout);
final Button button = (Button) findViewById(R.id.next);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (v==Bnext){sms_id=sms_id+1;}
}
});
}
}.... and the rest of the code
But when I click the button, nothing happend.
hey, my idea seems to be a bad idea so I try this way:
Code:
public class MySMSwidget extends AppWidgetProvider {
private int sms_id=0;
public void onReceive (Context context, Intent intent){
if (Intent.ACTION_ATTACH_DATA.equals(intent.getAction()))
{
Bundle extra = intent.getExtras();
sms_id = extra.getInt("Data");
}
}
public void onUpdate(Context context, AppWidgetManager
appWidgetManager, int[] appWidgetIds) {
Cursor c = context.getContentResolver().query(Uri.parse("content://
sms/inbox"), null, null ,null,null);
String body = null;
String number = null;
String date = null;
c.moveToPosition(sms_id);
body = c.getString(c.getColumnIndexOrThrow("body")).toString();
number =
c.getString(c.getColumnIndexOrThrow("address")).toString();
date = c.getString(c.getColumnIndexOrThrow("date")).toString();
c.close();
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
updateViews.setTextColor(R.id.text, 0xFF000000);
updateViews.setTextViewText(R.id.text,date+'\n'+number+'\n'+body);
ComponentName thisWidget = new ComponentName(context,
MySMSwidget.class);
appWidgetManager.updateAppWidget(thisWidget, updateViews);
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_ATTACH_DATA);
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
views.setOnClickPendingIntent(R.id.next, changeData(context));
}
private PendingIntent changeData(Context context) {
Intent Next = new Intent();
Next.putExtra("Data", sms_id+1);
Next.setAction(Intent.ACTION_ATTACH_DATA);
return(PendingIntent.getBroadcast(context,
0, Next, PendingIntent.FLAG_UPDATE_CURRENT));
}
}
my code isn't terminated.
I hope there will be someone to help to correct it.
Just want to display next SMS.
Please help.

[Q] AlertDialog (-> list with a lot of elements) how to handle orientation-change

Hi,
A few weeks ago I started developing an Android app but I've gut one problem
If the user changed the orientation of his phone the Activity is of course newly created. If there is ProgressDialog opened, I simply open a new one and the user does not realize it, but if I show an AlertDialog containing a few hundred elements and the user scrolls a bit he/she will realize it after I recreate the AlertDialog because the dialog will start again with the first element and the user has to scroll newly to the element he wants.
How I handle the "ListDialog":
At first I have two classes which simplify the ListDialog because I use it a few times...
ListDialog class:
Code:
public class ListDialog {
public static int CHOOSE_MODE_ONLINE = 0x01;
public static int CHOOSE_MODE_BOOKMARK = 0x02;
public static int CHOOSE_MODE_LOCAL = 0x03;
public static int CHOOSE_CHAPTER_ONLINE_DOWNLOAD = 0x04;
public static int CHOOSE_CHAPTER_BOOKMARK_DOWNLOAD = 0x05;
public static int CHOOSE_CHAPTER_ONLINE_READ = 0x06;
public static int CHOOSE_CHAPTER_BOOKMARK_READ = 0x07;
public static int CHOOSE_CHAPTER_LOCAL_READ = 0x08;
public static int CHOOSE_CHAPTER_LOCAL_DELETE = 0x09;
public static int GOTO_PAGE = 0x0A;
public static void show(Context context, String title, CharSequence[] elems, final ListMethodInvoker invoker)
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setItems(elems, new DialogInterface.OnClickListener() {
%mail%Override
public void onClick(DialogInterface dialog, int which) {
invoker.invoke(which);
}
});
builder.setOnCancelListener(new OnCancelListener() {
%mail%Override
public void onCancel(DialogInterface dialog) {
invoker.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
ListMethodInvoker class:
Code:
public class ListMethodInvoker {
public void invoke(int id)
{
}
public void cancel()
{
}
}
and now I create the dialog:
Code:
ApplicationController.get().addOpenedDialog(ListDialog.CHOOSE_MODE_ONLINE);
ListDialog.show(OnlineActivity.this,
mangaController.getManga().getMangaName(),
new CharSequence[]{"Add to Bookmarks", "Download a Chapter", "Read a Chapter"},
new ListMethodInvoker()
{
%mail%Override
public void invoke(int id)
{
ApplicationController.get().removeOpenedDialog(ListDialog.CHOOSE_MODE_ONLINE);
switch(id)
{
case 0: addBookmark(mangaController.getManga()); break;
case 1:
ApplicationController.get().addOpenedDialog(ListDialog.CHOOSE_CHAPTER_ONLINE_DOWNLOAD);
handleChapter(ChapterMode.Download);
break;
case 2:
ApplicationController.get().addOpenedDialog(ListDialog.CHOOSE_CHAPTER_ONLINE_READ);
handleChapter(ChapterMode.Read);
break;
}
}
%mail%Override
public void cancel()
{
ApplicationController.get().removeOpenedDialog(ListDialog.CHOOSE_MODE_ONLINE);
}
});
I also add the ID of the dialog to my ApplicationController which allows me to remember if a dialog has been openend and I can recreate it when onCreate(...) is called again.
(The ApplicationController uses the singleton design pattern which always allows me to retrieve the same instance of the ApplicationController.)
Thanks in advance
best regards
mike
btw: If you wonder why I write %mail% instead of the correct symbol, I get the following exception message if I use it: To prevent spam to the forums, new users are not permitted to post outside links in their messages. All new user accounts will be verified by moderators before this restriction is removed.

Cursor help!

I'm new to using cursors to obtain data from the device. I'm working on a music player (see market link in signature) and I need to be able to list (and eventually play) the music found on the sdcard. I have some code, but I can't seem to get it to work
Here's the code I found on a website, but it leads to a force-close:
public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView view = (TextView) findViewById(R.id.hello);
String[] projection = new String[] {
MediaStore.MediaColumns.DISPLAY_NAME
, MediaStore.MediaColumns.DATE_ADDED
, MediaStore.MediaColumns.MIME_TYPE
};
Cursor mCur = managedQuery(Media.EXTERNAL_CONTENT_URI,
projection, null, null, null
);
mCur.moveToFirst();
while (mCur.isAfterLast() == false) {
for (int i=0; i<mCur.getColumnCount(); i++) {
view.append("n" + mCur.getString(i));
}
mCur.moveToNext();
}
}
}
Here's my attempt at fixing it, which still leads to a force-close:
public class test3 extends Activity {
TextView view = (TextView) findViewById(R.id.text1);
ListView list;
private ArrayAdapter<String> adapter;
String[] projection = new String[] {
MediaStore.MediaColumns.DISPLAY_NAME
, MediaStore.MediaColumns.DATE_ADDED
, MediaStore.MediaColumns.MIME_TYPE
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ListView)findViewById(R.id.list);
ArrayList<String> _list = new ArrayList<String>(Arrays.asList(projection));
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,_list);
list.setAdapter(adapter);
Cursor mCur = managedQuery(Media.EXTERNAL_CONTENT_URI,
projection, null, null,
MediaStore.MediaColumns.DISPLAY_NAME + "ASC"
);
mCur.moveToFirst();
while (mCur.isAfterLast() == false) {
for (int i=0; i<mCur.getColumnCount(); i++) {
view.append("n" + mCur.getString(i));
}
mCur.moveToNext();
}
}
}
What am I doing wrong? Both codes lead to a force-close and I can't think of anything else to do. Thanks in advance.
did you set the correct permissions in the android manifest?
*slaps hand to forehead* I always forget about the manifest. Lol. Ummmm....what all am I supposed to put in there for these codes? Do both codes look like they would accomplish the same thing?
Well, I've written hundreds of Cursors in Android and I don't run my loop like you do, so, as a suggestion:
Code:
Cursror c = yada, yada;
if(c.moveToFirst()) {
do {
// TO DO HERE...
} while(c.moveToNext());
}
c.close();
Never had a problem.
Awesome! Thanks. Ill try it when I get a chance

SAP webservice consuming

Hi all ,
I am developing an android app to invoke a webservice in SAP side.i have deployed the webservice and i have sucessfully invoked it using soapui.i am connected to my sap network via vpn.when i try to invoke the webservice from eclipse in the emulator.i am getting an warning "UnknownHostException: Unable to resolve host "myhostaddress": No address associated with hostname".
here is the code i used
public class customer_complaint extends Activity {
/** Called when the activity is first created. */
private static String SOAP_ACTION1 = "";
private static String METHOD_NAME1 = "ZfmCoeMob";
private static String NAMESPACE = "urn:sap-com:document:sap:soap:functions:mc-style";
private static String URL = "hypertextprotocol://10.201.52.86:8003/sap/bc/srt/wsdl/bndg_E2C5751FB4DDC7F192D3000E0CB7EB52/wsdl11/allinone/ws_policy/document?sap-language=EN&sap-client=100&sap-user=abap&[email protected]";
Button submit;
EditText editText_Customer,editText_Invoice;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.customer_complaint);
submit = (Button)findViewById(R.id.submit);
editText_Customer = (EditText)findViewById(R.id.editText_Customer);
editText_Invoice = (EditText)findViewById(R.id.editText_Invoice);
submit.setOnClickListener(new View.OnClickListener()
{
@override
public void onClick(View v)
{
//Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
//Use this to add parameters
request.addProperty("ZfmCoeMob",editText_Customer.getText().toString());
//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION1, envelope);
// Get the SoapResult from the envelope body.
// SoapObject result = (SoapObject)envelope.bodyIn;
SoapPrimitive resultString = (SoapPrimitive)envelope.getResponse();
if(resultString != null)
{
//Get the first property and change the label text
// editText_Invoice.setText(result.getProperty(0).toString());
editText_Invoice.setText(resultString.toString());
}
else
{
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
is it something wrong due to the url link.but i am able to invoke the same service using soapui.i have attached my wsdl file with this thread.

How do I implement a onscroll Listener to my listview?

I have a large data to load from JSON.
I have implemented a custom list view by following a tutorial, now since the data is huge I want it load as the user scrolls.
This is my LoadRestaurant class code which is inside the main activity.
Code:
class LoadRestaurants extends AsyncTask<String, String, String> {
//Show Progress Dialog
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchAll.this);
pDialog.setMessage("Loading All Restaurants...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//dismiss the dialog
pDialog.dismiss();
//Updating UI from the Background Thread
runOnUiThread(new Runnable() {
@Override
public void run() {
ListAdapter adapter = new SimpleAdapter(
SearchAll.this, restaurant_list,
R.layout.listview_restaurants, new String[]{
TAG_ID, TAG_NAME, TAG_LOCATION, TAG_RATING}, new int[]{
R.id.login_id, R.id.restaurant_name, R.id.address, R.id.rating});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Bundle bundle = new Bundle();
Intent intent = new Intent(SearchAll.this, RestaurantProfile.class);
String loginId = ((TextView) view.findViewById(R.id.login_id)).getText().toString();
intent.putExtra("login_id", loginId);
startActivity(intent);
}
});
}
});
}
}
}
I want to load around 20 restaurants and then it auto loads another 20 as soon as user reaches the end of first 20.
There are lots of tutorials online but its confusing to implement.
Please help me out!
The custom ListView, support for automatic loading you can try https://github.com/chrisbanes/Android-PullToRefresh

Categories

Resources