How to retrieve listview using BaseAdapter? - android

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.

Related

gridview custom adapter search

i have grid view , and custom adapter i want to search the items that are in the grid view by a search view ,,,
the thing is i don't know how to implement a search view along with a custom adopter ,, because i have a click event in the custom adapter which is when the user clicks an item it downloads a pdf file form internet ,, how can i add search view that will search the grid view items in with the custom adapter click even running ,
i am new usually i copy and paste the code i am 30% new .
this is my main activity
package com.alhaddadsoft.ammar.gridview;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
GridView gv;
GridView gv1;
TextView newtext;
Context context;
ArrayList prgmName;
public static String [] prgmNameList={"احمد عبده ماهر","احمد داوود","احمد صبحي منصور","لكشف الموروث اقرأ هذا أولا","الختان للذكور والاناث","الصادق النيهوم","الطريق إلى بيت المقدس","اوشو","بن فرناس","جمال البنا","جورج طرابيشي","زكريا اوزون", "سلامه موسى","سلسلة عندما نَطَقَ السراة","عبد الرزاق جبران","عبد الله القصيمي","علي الوردي","علي شريعتي","فاضل الربيعي","فرج فوده","كمال الصليبي","محمد اركون","محمد شحرور","محمد علي المحمود","محمود ابو ريه","نيازي عز الدين","هشام جعيط"
,"أبو الأعلى المودودي - الخلافة والملك","أسوار الصمت قراءة في الحقوق المدنية في السعودية لـ د. وليد الماجد","احمد امين - فجر الاسلام","اعمدة الحكمة السبعة . لورنس العرب","الارهابى ",
" الاسلام واصول الحكم -- على عبد الرازق","الاسلام وجراب الحاوي . شاكر النابلسي","الاضافة النوعية القرانية.مصطفى بوهندي",
"التأثير المسيحي في تفسير القران","التوراة اليهودية مكشوفة على حقيقتها","الخلافه الاسلاميه.محمد سعيد عشماوي","الدولة الاسلامية ،الجذور والتوحش عبدالباري عطوان","الدين واحتكار الحقيقه.واثق غازي","السادس من نوفمبر قيادة المراة للسيارة","السلطة في الاسلام لعبدالجواد حسين","السلفيون ايضا يدخلون النار.وليد طوغان","السنة بين الاصول والتاريخ ذويب رسالة دكتوراة","العقل الايماني","القران وثالوث الاستبداد.نشأت جعفر",
"القران ولغة السريان. احمد علي الجمل","اللاهوت العربى-يوسف زيدان","المؤمن الصادق - إيريك هوفر","الملوك المحتسبون حجم صغير","امي كاملة عقل ودين","انتكاسة المسلمين الى الوثنية - سيد القمني","بالداخل . اشرف فياض","بالداخل . اشرف فياض","تاريخ نجد . بن غنام مؤرخ محمد بن عبدالوهاب","تحرير المرأه من عهد الرساله","تزييف الاسلام.انور اسحاق","جغرافية التوراة _زياد منى","حتى لا يعود جهيمان . توما ... غهامر . ستيفان لاكروا",
"حكاية التدين السعودي . وحيد الغامدي","حواء والخطيئة","حوار حول القران وحده . محمد توفيق صدقي","رجم الزاني","طبائع الإستبداد ومصارع الإستعباد","عبد الرزاق عيد .. سدنة هياكل الوهم , نقد العقل الفقهي","عبيد بلا اغلال.تاريخ جزيرة العرب القريب","فتنة القول بتعليم البنات.عبدالله الوشمي","قدماء المصريين اول الموحدين","كارثة فلسطين . عبدالله التل","لعبة الامم","ما بعد الشيوخ ، انهيار ممالك الخليج","مابعد الصحوة.عبدالله الغذامي","مشكلة الحديث","معجزة اختيار اللفظ في القرآن",
"مقالة العبودية الطوعية","من يجرؤ على الكلام .بول فندلي","نقد الخطاب الديني لنصر ابو زيد","نقد الخطاب السلفي ابن تيمية نموذجا.رائد السمهوري","ورثة محمد .جذور الخلاف السني الشيعي"
};
public static int [] prgmImages={R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon,R.drawable.folder_mac_icon
,R.drawable.book1,R.drawable.book2,R.drawable.book3,R.drawable.book4,R.drawable.book5,R.drawable.book6,R.drawable.book7,R.drawable.book8,R.drawable.book9,R.drawable.book10,R.drawable.book11,R.drawable.book12,R.drawable.book13,R.drawable.book14,R.drawable.book15,R.drawable.book16,R.drawable.book17,R.drawable.book18,R.drawable.book19,R.drawable.book20,R.drawable.book21_,R.drawable.book21,R.drawable.book22,R.drawable.book23,R.drawable.book24,R.drawable.book25,R.drawable.book26,R.drawable.book27,R.drawable.book28,R.drawable.book29,R.drawable.book30,R.drawable.book31,R.drawable.book32,R.drawable.book33,R.drawable.book34,R.drawable.book35,R.drawable.book36_,R.drawable.book36,R.drawable.book37,R.drawable.book38,R.drawable.book39,R.drawable.book40,R.drawable.book41,R.drawable.book42,R.drawable.book43,R.drawable.book44,R.drawable.book45,R.drawable.book46,R.drawable.book47,R.drawable.book48,R.drawable.book49,R.drawable.book50,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gv=(GridView) findViewById(R.id.gridView1);
gv.setAdapter(new CustomAdapter(this, prgmNameList, prgmImages));
}
public void openactivity1(){
edittext();
//Intent i = new Intent(this, AhmedDaod.class);
// startActivity(i);
}
public void edittext(){
// newtext = (TextView)findViewById(R.id.textView5);
// newtext.setText("hello");
}
}
This is my CustomAdapter acteivity
package com.alhaddadsoft.ammar.gridview;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
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.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class CustomAdapter extends BaseAdapter {
String[] result;
Context context;
int[] imageId;
private static LayoutInflater inflater = null;
String dwnload_file_path;
String file_name;
String imageViewD;
String textViewD;
GridView gridview;
public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, int[] prgmImages ) {
// TODO Auto-generated constructor stub
result = prgmNameList;
context = mainActivity;
imageId = prgmImages;
inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView tv;
ImageView img;
TextView edit ;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.programlist, null);
holder.tv = (TextView) rowView.findViewById(R.id.textView1);
holder.img = (ImageView) rowView.findViewById(R.id.imageView1);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId[position]);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(context, "You Clicked " + result[position], Toast.LENGTH_LONG).show();
// String displayedText = ((TextView)((LinearLayout)myToast.getView()).getChildAt(0)).getText().toString();
try {
if (result[position].equals("أبو الأعلى المودودي - الخلافة والملك")) {
new AlertDialog.Builder(context)
.setTitle("تحميل الكتاب")
.setMessage("هل تريد تحميل الكتاب?")
.setPositiveButton("تحميل", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
dwnload_file_path = "http://www.jouhinabooks.com/get_file.php?id=470";
file_name = "book1.pdf";
imageViewD = "book1";
textViewD = result[position];
Downloadmethode();
}
})
.setNegativeButton("رجوع", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
//Intent intent= new Intent(context, AhmedDaod.class);
// intent.putextra("your_extra","your_class_value");
//context.startActivity(intent);
//MainActivity openactivity = new MainActivity();
// openactivity.openactivity1();
//edittext.setText("hello");
}
} catch (final Exception e) {
Toast.makeText(context, "error ", Toast.LENGTH_LONG).show();
}
}
});
return rowView;
}
public void Downloadmethode(){
Intent d = new Intent(context, DownloadBook.class);
d.putExtra("dwnload_file_path", dwnload_file_path);
d.putExtra("file_name", file_name);
d.putExtra("imageViewD",imageViewD);
d.putExtra("textViewD",textViewD);
context.startActivity(d);
}
}
This is how I implemented the search feature. Create two Lists, the searchList and the backUpList.
backUpList = loadMyData();
searchList.addAll(backUpList);
Now you have two lists that contain the same data. And because the lists contain only references to the objects there is no extra memory being used. Then feed the searchList to the adapter instead of the actual list.
adapter = new CustomAdapter(searchList*/,...other inputs*/);
gridView.setAdapter(adapter);
And now when you want to search in your data you empty your search list and search in you back up list. If an object should be shown then add it in your search list. Then notify the adapter and your search results are shown.
searchList.clear();
searchList.addAll(backUpList);
for(CustomObject object:backUpList){
if(meetsSearchCriteria(object)){
searchList.add(object);
}
}
adapter.notifyDataSetChanged();
And adjust the rest of your code to work with the searchList instead of the actual data list.
You must change your adapter to take an ArrayList of objects as input and not a table as your code shows. Tables do not support changes in their size after their creation.

Android - Pull to refresh within a tabbed fragment

I'm trying to make a refresh while sliding down on the top of the listview possible. I followed this link to make it work and it does on an activty. But I need it on fragments that are tabbed within a main activity so I cannot as the example shows use this method on my fragments.
Here's the correct code while using an activity:
TestActivity.java
import java.util.ArrayList;
import java.util.List;
import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Fragment;
import android.app.ListFragment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class TestActivity extends BaseActivity {
#Override
protected Fragment getSampleFragment() {
return new SimpleListFragment();
}
public static class SimpleListFragment extends ListFragment implements
OnRefreshListener {
int i = 0;
private PullToRefreshLayout mPullToRefreshLayout;
ArrayAdapter<String> adapter;
List<String> list;
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
list = new ArrayList<String>();
int no = 1;
for (int i = 0; i < 5; i++) {
list.add("Item No :" + no++);
}
super.onViewCreated(view, savedInstanceState);
ViewGroup viewGroup = (ViewGroup) view;
// As we're using a ListFragment we create a PullToRefreshLayout
// manually
mPullToRefreshLayout = new PullToRefreshLayout(
viewGroup.getContext());
// We can now setup the PullToRefreshLayout
ActionBarPullToRefresh
.from(getActivity())
// We need to insert the PullToRefreshLayout into the
// Fragment's ViewGroup
.insertLayoutInto(viewGroup)
// Here we mark just the ListView and it's Empty View as
// pullable
.theseChildrenArePullable(android.R.id.list,
android.R.id.empty).listener(this)
.setup(mPullToRefreshLayout);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, list);
// Set the List Adapter to display the sample items
setListAdapter(adapter);
setListShownNoAnimation(true);
}
#Override
public void onRefreshStarted(View view) {
// TODO Auto-generated method stub
// setListShown(false); // This will hide the listview and visible a
// round progress bar
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(5000); // 5 seconds
int itemNo = list.size();
itemNo++;
list.add("New Item No :" + itemNo);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
adapter.notifyDataSetChanged();
// Notify PullToRefreshLayout that the refresh has finished
mPullToRefreshLayout.setRefreshComplete();
// if you set the "setListShown(false)" then you have to
// uncomment the below code segment
// if (getView() != null) {
// // Show the list again
// setListShown(true);
// }
}
}.execute();
}
}
}
I've already tried multiple times to make this method work in my fragment code but I cannot succeed. The code below is a working fragment example without any input of the TestActivity.
InfoFragment.java
import java.util.ArrayList;
import java.util.List;
import com.example.app.Config;
...
import android.app.Activity;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
public class TicketInfoFragment extends Fragment {
List<Info> ticketInfo;
TicketFull ticket = new TicketFull();
private DatabaseHelper db;
int ticketId = TicketActivity.getCurrentTicketId();
String androidId;
String authCode;
String platform_url;
int uId;
View rootView;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
db = new DatabaseHelper(getActivity());
androidId = Secure.getString(getActivity().getContentResolver(),
Secure.ANDROID_ID);
Config config = new Config();
config = db.getConfig(androidId);
authCode = config.getAuthCode();
platform_url = config.getPlatformURL();
uId = config.getuId();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_ticket_information, container, false);
fillTicket();
return rootView;
}
private void fillTicket() {
HttpReader httpReader = new HttpReader();
httpReader
.setOnResultReadyListener(new HttpReader.OnResultReadyListener() {
#Override
public void resultReady(String result) {
JsonHelper jsonHelper = new JsonHelper();
ticket = jsonHelper.getTicket(result);
//showTicket();
fillSettings();
}
});
httpReader
.execute("http://aa.domainlink.com:1324/example/API/v1/json.php?auth=example&a=ticket&uauth="
+ authCode + "&uid=" + uId + "&id=" + ticketId);
}
private void readSettings() {
InfoAdapter infoAdapter = new InfoAdapter(
getActivity(), ticketInfo);
final ListView listViewInfo = (ListView) rootView.findViewById(R.id.listViewInfo);
listViewInfo.setAdapter(infoAdapter);
listViewInfo
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parentView,
View childView, int position, long id) {
}
});
listViewInfo.setEmptyView(rootView.findViewById(R.id.empty));
}
private void fillSettings() {
String dueDate = getString(R.string.noDueDate);
ticketInfo = new ArrayList<Info>();
ticketInfo.add(new Info(getString(R.string.ticket_subject), ticket.getSubject() + ""));
ticketInfo.add(new Info(getString(R.string.ticket_relation), ticket.getRelation() + ""));
ticketInfo.add(new Info(getString(R.string.ticket_status), ticket.getStatus() + ""));
ticketInfo.add(new Info(getString(R.string.ticket_priority), ticket.getPriority() + ""));
ticketInfo.add(new Info(getString(R.string.ticket_created), ticket.getTicketCreate() + ""));
ticketInfo.add(new Info(getString(R.string.ticket_department), ticket.getDepartmentName() + ""));
ticketInfo.add(new Info(getString(R.string.ticket_user), ticket.getUser() + ""));
if (!ticket.getDueDate().equals("00-00-0000 00:00:00")) {
dueDate = ticket.getDueDate();
}
ticketInfo.add(new Info(getString(R.string.ticket_dueDate), dueDate));
readSettings();
}
}
The BaseActivity that the activity normally requires:
BaseActivity.java
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class BaseActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Add the Sample Fragment if there is one
Fragment sampleFragment = getSampleFragment();
if (sampleFragment != null) {
getFragmentManager().beginTransaction()
.replace(android.R.id.content, sampleFragment).commit();
}
}
//This method will override by child class. Then base class can get the fragment
protected Fragment getSampleFragment() {
return null;
}
}
Posting my failed tries on implementing the activity method in my fragments would not work I guess so I do not post them.
If anyone of you could help thanks alot.
Android SDK has finally added SwipeRefreshLayout. Maybe you can add this to your layout?
http://developer.android.com/reference/android/support/v4/widget/SwipeRefreshLayout.html

Listview onItemClick Event not firing

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.

How to fetch data from Api into listview?

When i am trying to call the method "refresh" of main activity from another Api class,the method was called and also it shows some fatal errors.And it didn't change the adapter values.Can anyone give any idea to clear that.?
package com.example.hotspot;
import com.example.hotspot.HotspotApi;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
import android.widget.TextView;
public class HotSpot extends Activity {
TextView textview;
ListView listview;
HotspotAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hot_spot);
textview = (TextView) findViewById(R.id.textView1);
listview = (ListView) findViewById(R.id.listView1);
adapter = new HotspotAdapter(this);
listview.setAdapter(adapter);
new HotspotApi(adapter).execute();
}
public void refresh() {
System.out.println("refresh() is called");
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.hot_spot, menu);
return true;
}
}
hotspot.java
package com.example.hotspot;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.hotspot.HotspotModel;
import com.example.hotspot.HotspotAdapter;
import android.os.AsyncTask;
public class HotspotApi extends AsyncTask<Void, Integer, Void> implements
Icommon {
public Boolean IsServerErr = false;
private JSONArray response_array;
String url = "some url";
HotspotAdapter adapter;
HotSpot hot;
public HotspotApi(HotspotAdapter adapter) {
this.adapter = adapter;
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
getresult();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
hot=new HotSpot();
hot.refresh();
super.onPostExecute(result);
}
void getresult() {
InternetManager manager = new InternetManager(url);
String category_jsonresponse = manager.URLRequest();
if (!manager.IsServerConn) {
IsServerErr = true;
}
if (category_jsonresponse != null) {
System.out.println("Hotspot_jsonresponse" + category_jsonresponse);
try {
response_array = new JSONArray(category_jsonresponse);
for (int i = 1; i < response_array.length(); i++) {
JSONObject image_object = response_array.getJSONObject(i);
HotspotModel h = new HotspotModel();
h.setId(image_object.getString("id") == null ? ""
: image_object.getString("id"));
h.setContent(image_object.getString("content") == null ? ""
: image_object.getString("content"));
h.setImg(image_object.getString("img") == null ? ""
: image_object.getString("img"));
h.setName(image_object.getString("name") == null ? ""
: image_object.getString("name"));
arraylist.add(h);
}
System.out.println("HotspotModelsize() is " + arraylist.size());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
HotspotAdapter.java
package com.example.hotspot;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class HotspotAdapter extends BaseAdapter implements Icommon{
private TextView textview;
private View view;
ImageView imageview;
private LayoutInflater inflater;
public HotspotAdapter(Context context ){
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arraylist.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arraylist.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
if (arg1 == null) {
view = inflater.inflate(R.layout.custom_layout, null);
} else {
view = arg1;
}
textview = (TextView) view.findViewById(R.id.txt_content);
textview.setText(arraylist.get(arg0).getName());
return view;
}
}
In your HotSpotApi class you are creating a new HotSpot activity, this seems wrong. I guess that you are getting json data from internet and load it into a listview.
Solution:
In HotspotApi change following instead of calling activity method:
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
adapter.notfiyDatasetChanged();
}
Hope this will help you.
hot=new HotSpot(); ?? you cannot use like that! HotSpot is an activity, should be called by Framework for example, activitymanager. Or use startActivity() to show a activity.
Refresh method (adapter.notifyDataSetChanged();) will result in refresh of UI. However, hot = new HotSpot() will not call onCreated() method,which means the UI is not created. So it definitely results in the fatal error.
I'd never see anyone call an Activity with new operator.
You should reference the common process about how use a activity and adapter.

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) {
}

Categories

Resources