Listview onItemClick Event not firing - android

I have set an event listener(onclick) for the listview but it is not firing.
Below is my code. I have put logcat entry as the test. But the log entry not printed and the new activity not started.
public class GetTenantList extends Activity implements OnItemClickListener {
private static String DB_NAME="meterapp.sqlite";
DatabaseHelperClass db= new DatabaseHelperClass( this,DB_NAME);
allTenants individualreadings;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tenants);
allTenants individualreadings= new allTenants(this);
ListView listview =(ListView)findViewById(R.id.tenants);
listview.setBackgroundColor(color.holo_orange_dark);
listview.setAdapter(individualreadings);
listview.setOnItemClickListener(this) ;
}
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
protected void onPause() {
db.close();
super.onPause();
}
#Override
protected void onDestroy(){
db.close();
super.onDestroy();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
db.close();
super.onStop();
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long index) {
Intent intent = new Intent(this,EditTenants.class);
Tenants tenant=(Tenants)individualreadings.getItem(position);
String tenantid= Integer.toString(tenant.get_id());
Log.e("Testing Intent Filter", tenantid);
intent.putExtra("id", tenantid);
startActivity(intent);
}
}
Any reasons why it is not responding?
Ronald
I have two versions of code suggestions
Version 1
package com.example.metermanager;
import meter.manager.helper.DatabaseHelperClass;
import meters.model.Tenants;
import android.R.color;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class GetTenantList extends Activity {
private static String DB_NAME="meterapp.sqlite";
DatabaseHelperClass db= new DatabaseHelperClass( this,DB_NAME);
allTenants individualreadings;
ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tenants);
final allTenants individualreadings= new allTenants(this);
listview =(ListView)findViewById(R.id.tenants);
listview.setAdapter(individualreadings);
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id)
{
//whatever code you wish to invoke, in this case
Intent intent = new Intent(getApplicationContext(),EditTenants.class);
Tenants tenant=(Tenants)individualreadings.getItem(position);
String tenantid= Integer.toString(tenant.get_id());
Log.e("Testing Intent Filter", tenantid);
intent.putExtra("id", tenantid);
startActivity(intent);
}
});
}
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
protected void onPause() {
db.close();
super.onPause();
}
#Override
protected void onDestroy(){
db.close();
super.onDestroy();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
db.close();
super.onStop();
}
}
Version 2:
i am. Copied wrong code. Did not save it!
Both have failed.
Version 2;
package com.example.metermanager;
import meter.manager.helper.DatabaseHelperClass;
import meters.model.Tenants;
import android.R.color;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class GetTenantList extends Activity implements OnItemClickListener {
private static String DB_NAME="meterapp.sqlite";
DatabaseHelperClass db= new DatabaseHelperClass( this,DB_NAME);
allTenants individualreadings;
ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tenants);
final allTenants individualreadings= new allTenants(this);
listview =(ListView)findViewById(R.id.tenants);
listview.setAdapter(individualreadings);
listview.setOnItemClickListener(this);
}
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
protected void onPause() {
db.close();
super.onPause();
}
#Override
protected void onDestroy(){
db.close();
super.onDestroy();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
db.close();
super.onStop();
}
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id)
{
//whatever code you wish to invoke, in this case
Intent intent = new Intent(getApplicationContext(),EditTenants.class);
Tenants tenant=(Tenants)individualreadings.getItem(position);
String tenantid= Integer.toString(tenant.get_id());
Log.e("Testing Intent Filter", tenantid);
intent.putExtra("id", tenantid);
startActivity(intent);
}
}
Here is the code for allTenants class.
package com.example.metermanager;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import meter.manager.helper.DatabaseHelperClass;
import meters.model.Tenants;
import meters.model.VMeterReadings;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
public class allTenants extends BaseAdapter {
#SuppressWarnings("unused")
private Context context;
DatabaseHelperClass db;
private static String DB_NAME="meterapp.sqlite";
private List<Tenants> readings =new ArrayList<Tenants>();
DecimalFormat df = new DecimalFormat("#,###,###,###");
SimpleDateFormat fm =new SimpleDateFormat("dd-MM-yyyy",Locale.UK);
public allTenants(Context context1) {
this.context=context1;
DatabaseHelperClass db= new DatabaseHelperClass( context1,DB_NAME);
readings=db.GetAllTenants();
//close it
db.close();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return readings.size();
}
#Override
public Object getItem(int index) {
// TODO Auto-generated method stub
return getItem(index);
}
#Override
public long getItemId(int index) {
// TODO Auto-generated method stub
return index;
}
#Override
public View getView(int arg0, View view, ViewGroup parent) {
try{
if (view ==null){
LayoutInflater inflater=
LayoutInflater.from(parent.getContext());
view =inflater.inflate(R.layout.tenants_listview,parent,false);
}
Tenants reading =readings.get(arg0);
TextView tenantTextView =(TextView)
view.findViewById(R.id.textView9);
tenantTextView.setText(reading.getFirstName());
TextView surnameTextView =(TextView)
view.findViewById(R.id.textView10);
surnameTextView .setText(reading.getSurName());
TextView othernamesTextView =(TextView)
view.findViewById(R.id.textView11);
othernamesTextView .setText(reading.getOtherNames());
TextView mobile1 =(TextView)
view.findViewById(R.id.textView12);
mobile1.setText(reading.getMobile1());
TextView mobile2TextView =(TextView)
view.findViewById(R.id.textView13);
mobile2TextView.setText(reading.getMobile2());
TextView dateaddedTextView =(TextView)
view.findViewById(R.id.textView14);
dateaddedTextView.setText(fm.format((reading.getDateAdded())));
CheckBox inactiveCheckbox =(CheckBox)
view.findViewById(R.id.chkinactive);
inactiveCheckbox.setChecked(reading.getInActive());
TextView inactivedateTextView =(TextView)
view.findViewById(R.id.textView16);
inactivedateTextView.setText(fm.format(reading.getDateInActive()));
TextView tenantid =(TextView)
view.findViewById(R.id.textView17);
String test= Integer.toString(reading.get_id());
tenantid.setText(test);
}catch(Exception e)
{
Log.e("Error loading data in All Tenants listbox",e.toString());
}
return view;
}
}

Check like this:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(GetTenantList.this,EditTenants.class);
Tenants tenant=(Tenants)individualreadings.getItem(position);
String tenantid= Integer.toString(tenant.get_id());
Log.e("Testing Intent Filter", tenantid);
intent.putExtra("id", tenantid);
startActivity(intent);
}

You are using just this as context.... change it to GetTenantList.this in your onItemClick. Also, you can change the intent parameters to:
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long index) {
Intent intent = new Intent(GetTenantList.this,EditTenants.class);
Tenants tenant=(Tenants)individualreadings.getItem(position);
String tenantid= Integer.toString(tenant.get_id());
Log.e("Testing Intent Filter", tenantid);
Bundle params = new Bundle();
params.putString("id", tenantid);
intent.putExtras(params);
startActivity(intent);
}

I think you may have misread the setOnItemClickListener() documentation/examples. Try doing it like this:
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id)
{
//whatever code you wish to invoke, in this case
Intent intent = new Intent(getApplicationContext(),EditTenants.class);
Tenants tenant=(Tenants)individualreadings.getItem(position);
String tenantid= Integer.toString(tenant.get_id());
Log.e("Testing Intent Filter", tenantid);
intent.putExtra("id", tenantid);
startActivity(intent);
}
}
Don't forget to properly import the listener too!

Try using the ListView as member variable of the class.

Related

error unresolved type, how to initialise dbhelper?

I am following a tutorial for sqllite tutorial database.
here is the code offered by the tutorial.
package com.example.addressbook;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.AddressBook.MESSAGE";
private ListView obj;
DBHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new DBHelper(this);
ArrayList array_list = mydb.getAllCotacts();
ArrayAdapter arrayAdapter =
new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
//adding it to the list view.
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(),com.example.addressbook.DisplayContact.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mainmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.item1:
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(getApplicationContext(),com.example.addressbook.DisplayContact.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
}
when I am applying it ,I am having error:
DBHelper mydb;
DBHelper unresolved type.
How then to declare DBHelper? Where is the problem with my code
In the tutorial you can find this:
Datbase - Helper class
For managing all the operations related to the datbase , an helper class has been given and is called SQLiteOpenHelper. It automatically manages the >creation and updation of the datbase. Its syntax is given below
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db) {}
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}
}
in the Example section you can find the class DBHelper implemented.

How I can remove items of ListView?

The apk is a memo pad or something like that. First you can put the title and then the note and if you press the button "Save" the note is saved and it saves in database. And if you press the button "Notes", you can view a list with all notes saved in database and you can select all notes and in the top of screen, you can read how many notes are selected. Ok, it's fine but I need remove notes when the are selected and I press the button with bin icon in the top menu.
The code:
package com.example.u2tarea3;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class AnotacionesOpenHelperSingleton extends SQLiteOpenHelper {
private static AnotacionesOpenHelperSingleton instancia = null;
private Context mCtx;
public static AnotacionesOpenHelperSingleton getInstance(Context ctx){
if(instancia == null){
instancia = new AnotacionesOpenHelperSingleton(ctx);
}
return instancia;
}
private AnotacionesOpenHelperSingleton(Context ctx) {
super(ctx,"anotaciones",null,2);
}
#Override
public void onCreate(SQLiteDatabase bd) {
StringBuilder sql = new StringBuilder();
sql.append("create table IF NOT EXISTS anotaciones (");
sql.append("_id integer primary key autoincrement,");
sql.append("texto text not null,");
sql.append("fecha text not null)");
bd.execSQL(sql.toString());
}
#Override
public void onUpgrade(SQLiteDatabase bd, int oldVersion, int newVersion) {
//bd.execSQL("drop table anotaciones");
bd.execSQL("ALTER TABLE anotaciones ADD titulo text");
bd.execSQL("UPDATE anotaciones SET titulo = 'sin titulo' WHERE titulo is NULL");
onCreate(bd);
}
}
package com.example.u2tarea3;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText editText;
EditText editTitulo;
Button btnGuardar;
Button btnAnotaciones;
SQLiteDatabase bd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AnotacionesOpenHelperSingleton openHelperSingleton = AnotacionesOpenHelperSingleton.getInstance(this);
bd = openHelperSingleton.getWritableDatabase();
editText = (EditText)findViewById(R.id.editText);
editTitulo = (EditText) findViewById(R.id.editTitulo);
btnGuardar = (Button) findViewById(R.id.btnGuardar);
btnGuardar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
ContentValues valores = new ContentValues();
valores.put("texto", editText.getText().toString());
valores.put("fecha", sdf.format(c.getTime()));
valores.put("titulo", editTitulo.getText().toString());
bd.insert("anotaciones", null, valores);
editText.setText("");
}
});
btnAnotaciones = (Button) findViewById(R.id.btnAnotaciones);
btnAnotaciones.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,ListAnotaciones.class);
startActivity(intent);
}
});
}
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main,menu);
return true;
}
}
package com.example.u2tarea3;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class ListAnotaciones extends ListActivity {
SQLiteDatabase bd;
Cursor cursor;
AnotacionesOpenHelperSingleton openHelperSingleton = AnotacionesOpenHelperSingleton
.getInstance(this);
int cont = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bd = openHelperSingleton.getReadableDatabase();
cursor = bd.rawQuery("SELECT * FROM anotaciones", null);
try {
String[] from = { "fecha", "titulo" };
int[] to = { R.id.anotacionesFecha, R.id.anotacionesTitulo };
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.anotacion, cursor, from, to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setListAdapter(adapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(
new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode arg0,
Menu arg1) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onDestroyActionMode(ActionMode arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateActionMode(ActionMode arg0,
Menu arg1) {
// TODO Auto-generated method stub
MenuInflater inflater = arg0.getMenuInflater();
inflater.inflate(R.menu.anotaciones, arg1);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode arg0, MenuItem arg1) {
switch(arg1.getItemId()){
case R.id.delete_id:
//arg0.finish();
default:
break;
}
return true;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
int seleccionados = getListView()
.getCheckedItemCount();
switch (seleccionados) {
case 1:
mode.setTitle("1 nota seleccionada");
break;
default:
mode.setTitle("" + seleccionados
+ " notas seleccionadas");
break;
}
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.anotaciones, menu);
return true;
}
}
You'll need to remove the note from the database and the ListView, and then call ListViewAdapter.notifyDataSetChanged()
To delete from the datasource have a method in the class that deals with the datasource:
/**
* Delete a note given an id.
* #param id Key used to identify a note to delete.
*/
public void deleteNote(long id) {
System.out.println("Note deleted with id: " + id);
database.delete(ListOpenHelper.TABLE_MEMOS,
ListOpenHelper.ID + " = " + id,
null);
}
To refresh the ListView you could simply clear and re-add all the Views via the ListViewAdapter:
// Refresh adapter view with new data
ListAdapter.clear();
ListAdapter.addAll(dataSource.getAllNotes());
ListAdapter.notifyDataSetChanged();
Alternatively remove only a single element from the ListViewAdapter and call notifyDataSetChanged();.

Calling activitygroup from customlistadapter

I am working on an android app which is having functionality of tabs.
Everything is working fine but I am not able to call activtygroup from listadapter.
Here is my code for list adapter:
import java.util.ArrayList;
import android.app.Activity;
import android.app.ActivityGroup;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.tv.socialgoal.R;
import com.tv.socialgoal.imageloader.ImageLoader;
public class AllyListAdapter extends BaseAdapter{
Activity ctx;
ArrayList<Object> alist;
private ImageLoader imageLoader;
AllyBean allyBean;
private String photoPath;
public AllyListAdapter(Activity ctx, ArrayList<Object> alist) {
super();
this.ctx = ctx;
this.alist = alist;
imageLoader=new ImageLoader(ctx);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return alist.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View arg1, ViewGroup arg2) {
LayoutInflater linf=(LayoutInflater) ctx.getSystemService(ctx.LAYOUT_INFLATER_SERVICE);
View v=linf.inflate(R.layout.ally_list_row, null);
TextView tv=(TextView)v.findViewById(R.id.allyName);
ImageView profileImage=(ImageView)v.findViewById(R.id.ally_image);
Button inviteBtn=(Button)v.findViewById(R.id.invite_btn);
//SHOW DATA FROM LIST
allyBean=(AllyBean)alist.get(position);
tv.setText(allyBean.getName());
photoPath=allyBean.getAvatar();
profileImage.setTag(photoPath);
imageLoader.displayImage(photoPath, ctx, profileImage, false);
inviteBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent=new Intent(ctx,AddRemoveFriendScreen.class);
//intent.putExtra("friendId", allyBean.getUserId());
ctx.startActivity(intent);
}
});
return v;
}
/*public void replaceContentView(String id, Intent newIntent) {
View view =getLocalActivityManager().startActivity(id,
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
this.setContentView(view);
}*/
}
Now I have to call AddRemoveFriends activtygroup.
Here is the code for activtygroup:
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActivityGroup;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.tv.servercommunication.IServerResponse;
import com.tv.servercommunication.WebServiceCommunicator;
import com.tv.socialgoal.Constant;
import com.tv.socialgoal.R;
import com.tv.socialgoal.network.NetworkAvailablity;
import com.tv.task.TabViewActivity;
public class AddRemoveFriendScreen extends ActivityGroup implements OnClickListener, IServerResponse{
Button backBtn;
Button addRemoveFriendBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friends_profile_screen);
backBtn=(Button)findViewById(R.id.back_button);
addRemoveFriendBtn=(Button)findViewById(R.id.add_remove_frnd_btn);
backBtn.setOnClickListener(this);
addRemoveFriendBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.back_button:
break;
case R.id.add_remove_frnd_btn:
callAddFriend_WS();
break;
default:
break;
}
}
private Handler _handler = new Handler() {
public void dispatchMessage(Message msg) {
switch (msg.arg1) {
case Constant.PID_ADD_REMOVE_FRIEND:
if (parseResponse(msg.obj.toString()) == true) {
Intent intent = new Intent(getParent(),
TabViewActivity.class);
startActivity(intent);
} else {
runOnUiThread(new Runnable() {
public void run() {
Constant.showAlertDialog(
Constant.DIALOG_TITLE_ERROR,
"Invalid username or password.",
getParent(), false);
}
});
}
break;
default:
break;
}
}
};
// GET USER ACCESSTOCKEN AND USER ID
private boolean parseResponse(String response) {
String message = null;
JSONObject post;
boolean isUserInfoAvail = false;
try {
JSONObject postjsonObject = new JSONObject(response);
JSONObject posts = postjsonObject.getJSONObject("posts");
post = posts.getJSONObject("post");
message = post.getString("message");
if (message.equalsIgnoreCase("failure")) {
isUserInfoAvail = false;
} else {
isUserInfoAvail = true;
}
} catch (JSONException e1) {
e1.printStackTrace();
}
return isUserInfoAvail;
}
public void callAddFriend_WS() {
if (NetworkAvailablity.checkNetworkStatus(AddRemoveFriendScreen.this)) {
// PREPARE URL
Constant.methodURL = "http://admin.tvdevphp.com/goalmachine/add_friend.php";
// PREPARE REQUEST PARAMETER
ArrayList<NameValuePair> requestParaList = new ArrayList<NameValuePair>();
requestParaList.add(new BasicNameValuePair("self_user_id", "1"));
requestParaList.add(new BasicNameValuePair("user_friend_id", "2"));
// CALL WEBSERVICE
WebServiceCommunicator.getInstance().registerForServerResponse(
AddRemoveFriendScreen.this);
WebServiceCommunicator.getInstance().callGetAppWebService(
Constant.showDialog, getParent(),
Constant.methodURL, getParent(), Constant.PID_ADD_REMOVE_FRIEND,
false, requestParaList);
} else {
Constant.showAlertDialog(Constant.errorTitle,
Constant.MSG_CHECK_INTERNET_SETTING, getParent(),
false);
}
}
// SERVER RESPONSE METHOD
public void serverResponse(String response, int processid) {
Message msg = new Message();
msg.arg1 = processid;
msg.obj = response;
_handler.dispatchMessage(msg);
}
}
Please suggest me how to call activtygroup from listadapter.
Make it like this you can access everything by doing like this.
public class AddRemoveFriendScreen extends ActivityGroup implements OnClickListener, IServerResponse
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
.......
}
class AllyListAdapter extends BaseAdapter
{
//Now you can call everything from ActivityGroup
}
}
Hope this will help you.
According to the android developper reference, you may use Fragments.
ActivityGroup is deprecated. Use the new Fragment and FragmentManager APIs instead; these are also available on older platforms through the Android compatibility package.
You can try this trick.
inviteBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(ctx instanceof ActivityGroup){
Intent intent = new Intent(ctx.getParent(),AddRemoveFriendScreen.class);
//intent.putExtra("friendId", allyBean.getUserId());
ctx.getParent().startActivity(intent);
}
else{
Intent intent = new Intent(ctx,AddRemoveFriendScreen.class);
//intent.putExtra("friendId", allyBean.getUserId());
ctx.startActivity(intent);
}
}
});
If it doesn't work just use internal class for your adapter in your AddRemoveFriendScreen class.

How to start two different Intents in alistView.setOnItemClickListener(new OnItemClickListener() {}

I am new to android and a little bit confused. i have a listView with image and text. Where, if I click on a Image it should start an activity, and if I click on text another activity.
Cod:
in
onCrete(){
listView = getListView();}
myBaseAdapterItemActivity = new MyBaseAdapterItemActivity(
ItemActivity.this, placeNameList);
setListAdapter(myBaseAdapterItemActivity);
myBaseAdapterItemActivity.notifyDataSetChanged();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
// One Activity I can start without any problem
// In xml File I set for image clicable to true.
// What I want to do is like this
if(view.getId() == R.id.imageId)
{
Intent intent = new Intent(this, ImageActivity.class);
startActivity(intent);
}
else if(view.getID == R.id.textId)
{
Intent intent = new Intent(this, TextActivity.class);
startActivity(intent);
}
}}
And whenever I click on Image it does not not either in textView.
Any Idea
It has two solutions:
1) Instead on writing onItemClickListener for list you can do findviewbyid the textview and imageview in your custom adapter in getview method and then set onclick listeners on both of them.
2) You can use getChildAt method.... and check which child is your imageview and which is your textview. This is a work around so not much guaranteed.
Try with the below code.
Your adapter should be like below code. then your text and image click will create new activity.
Hi the code should be like below Hope this helps you.
package com.example.listwithclick;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView listView1;
Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity=this;
listView1=(ListView)findViewById(R.id.listView1);
listView1.setAdapter(new MyAddapter(MainActivity.this));
}
#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;
}
class MyAddapter extends BaseAdapter {
Context rContext;
private LayoutInflater rInflater;
public MyAddapter(Context c) {
rInflater = LayoutInflater.from(c);
rContext = c;
}
public MyAddapter(Activity imagebinding) {
// TODO Auto-generated constructor stub
activity = imagebinding;
rContext = imagebinding;
rInflater = LayoutInflater.from(imagebinding);
rContext = imagebinding;
rInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 10;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
convertView = rInflater.inflate(R.layout.child, null);
final MyDat mydat = new MyDat();
mydat.textview = (TextView) convertView.findViewById(R.id.textView1);
mydat.textview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(rContext, "text", 1000).show();
Intent image= new Intent(rContext,TextActivity.class);
startActivity(image);
}
});
mydat.imageView1=(ImageView)convertView.findViewById(R.id.imageView1);
mydat.imageView1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(rContext, "image ", 1000).show();
Intent image= new Intent(rContext,ImageActivity.class);
startActivity(image);
}
});
return convertView;
}
class MyDat {
TextView textview;
ImageView imageView1;
}
}
}
In your MyBaseAdapterItemActivity, setOnClickListener((OnCLickListener)mContext) to the ImageVIew and TextView.
In your activity, extends OnClickListener.
write your startActivity(Intent) in the OnClick(View v) depending on v.getId()
In list item xml, for set android:onClick="onFirstLinkClick" and similarly for the image view also,
and the use following method in your activity
public void onFirstLinkClick(View V) {
}

How to retrieve listview using BaseAdapter?

I have created android apps to retrieving Listview using BaseAdapter from ArrayList but not displayed anything in Listview. Description of my apps is that I want retrieve listview using BaseAdapter. when my app is run on emulator nothing is displayed on screen when clicked on menu button on my emulator only add button displayed on screen after clicked on add launch the new activity in that activity i have created two editText. after submit, return to prev activity and display the listview.
Please can anybody help me to find out this error
Following is the Adapter class
package com.oj2.exlistview;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class TimeTrackAdapter extends BaseAdapter {
ArrayList<TimeRecord> times = new ArrayList<TimeRecord>();
public Context cntxt;
public TimeTrackAdapter(Context cnt,ArrayList<TimeRecord> list2) {
super();
cntxt = cnt;
times = list2;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return new TimeTracker().getList1().size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return getItem(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null){
System.out.println("in getView");
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
convertView = inflater.inflate(R.layout.time_list_item, parent,false);
TimeRecord time = times.get(position);
TextView timeTextView = (TextView) convertView.findViewById(R.id.timeView);
timeTextView.setText(time.getTimes());
TextView noteTextView = (TextView) convertView.findViewById(R.id.noteView);
noteTextView.setText(time.getNotes());
}
return convertView;
}
}
Following is the Activity class
package com.oj2.exlistview;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
public class TimeTracker extends Activity{
TimeTrackAdapter timeTrackAdapter;
ListView listView;
TimeRecord timerecord;
public ArrayList<TimeRecord> list1 = new ArrayList<TimeRecord>();
public static final int TIME_ENTRY_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
System.out.println("in onCreate()");
}
public ArrayList<TimeRecord> getList1() {
return list1;
}
public void setList1(ArrayList<TimeRecord> list1) {
this.list1 = list1;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
System.out.println("in onCreateOptionsMenu");
MenuInflater mI = getMenuInflater();
mI.inflate(R.menu.time_list_menu,menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
// TODO Auto-generated method stub
System.out.println("in onMenuItemSelected");
if (item.getItemId()==R.id.add_time_menu_item) {
Intent intent = new Intent(this, AddTimeActivity.class);
startActivityForResult(intent, TIME_ENTRY_REQUEST_CODE);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
System.out.println("in onActivityResult");
if (requestCode==TIME_ENTRY_REQUEST_CODE) {
if (resultCode==RESULT_OK) {
String Time = data.getStringExtra("time");
String Note = data.getStringExtra("note");
list1.add(new TimeRecord(Time, Note));
timeTrackAdapter = new TimeTrackAdapter(this,list1);
listView = (ListView) findViewById(R.id.timeListView);
listView.setAdapter(timeTrackAdapter);
listView.getAdapter();
/* timeTrackAdapter.addTimeRecord(new TimeRecord(Time, Note));*/
timeTrackAdapter.notifyDataSetChanged();
}
}
}
}
Following is the AddTimeActivity
package com.oj2.exlistview;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class AddTimeActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_time);
}
public void onCancle(View view) {
finish();
}
public void onSave(View view) {
Intent intent = getIntent();
EditText TimeView = (EditText) findViewById(R.id.editText1);
intent.putExtra("time", TimeView.getText().toString());
EditText Noteview = (EditText)findViewById(R.id.editText2);
intent.putExtra("note", Noteview.getText().toString());
this.setResult(RESULT_OK, intent);
finish();
}
}
Thanking You
First, don't create any Activity object in your Adapter. Activity objects are created by Android itself, and they are used to display Views. It has nothing to do with adapters.
The layout you want to display your data in must contain a <ListView ... /> tag, with an android:id="#+id/whatEverId" attribute.
Then what you have to do is to retrieve the ListView object in your TimeTracker activity using its id :
ListView lv = (ListView) findViewById(R.id.whatEverId);
Then create your adapter and tell your ListView that the views you want it to display will be created by your custom adapter :
TimeTrackerAdapter adapter = new TimeTrackerAdapter(this, myListOfData);
lv.setAdapter(adapter);
myListOfData is your ArrayList containing the data. The rest is explicit and should do the job.

Categories

Resources