gridview custom adapter search - android

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.

Related

How to select single item from listview and display resulted name of row in another activity

I got problem when trying to get checked item from listView through predefined xml layout simple_list_item_single_choice and select item then set text of a TextView that is in another activity.
This is my showMyUI method that call from MainActivity on click of TextView
dateRange.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(MainActivity.this, "Range clicked",Toast.LENGTH_SHORT).show();
DateRangeClass day=new DateRangeClass(MainActivity.this,dayRangeSelected);
day.showMyUI();
overridePendingTransition(R.anim.right_to_left, R.anim.left_to_right);
}
});
And my DateRangeClass is
package tutorial.projecttwofilter;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class DateRangeClass {
Context context;
LinearLayout backButton;
ListView rangeList;
TextView rangeText;
String[] dateRangeData= new String[]{"Next 7 Days", "Next 14 Days", "Next 30 Days"};
public DateRangeClass(Context context,TextView rangeText) {
this.context = context;
this.rangeText=rangeText;
}
public void showMyUI(){
((Activity)context).setContentView(R.layout.daterange);
backButton= (LinearLayout) ((Activity)context).findViewById(R.id.backButton);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((Activity) context).finish();
((Activity) context).overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
});
rangeList= (ListView) ((Activity)context).findViewById(R.id.dateRangeList);
ArrayAdapter<String> adapter= new ArrayAdapter<>(context, android.R.layout.simple_list_item_single_choice, dateRangeData);
rangeList.setAdapter(adapter);
rangeList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
rangeList.setItemChecked(position, true);
if(rangeList.isItemChecked(position))
Toast.makeText(context, "Checked item is"+rangeList.getCheckedItemPosition(), Toast.LENGTH_SHORT).show();
rangeText.setText("You new Change "+rangeList.getCheckedItemPosition());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(context, "Nothing selected", Toast.LENGTH_SHORT).show();
}
});
}
}
Create DateRangeClass as an activity not as normal class and pass the information using bundle. As i can see you are passing textview instead of that you can pass text as string and can show in second activity.
To transfer data
String textToBesend = "Text from textview";
Intent i = new Intent(this, DateRangeActivity.class);
i.putExtra("text", textToBesend);
startActivity(i);
and to recieve data in DateRangeActivity write this in oncreate method.
Intent intent = getIntent();
String textPassedFromFirstActivity = intent.getExtras().getString("text");
You can refer below tutorial for your purpose hope it helps.
passing data to activity from listview
You have not started your activity.
Use startActivity and putIntent method on button click and in your second activity use getIntent method to display the text.

Android list view current position doesn't work properly

I'm Getting data from my database and pushing them into ListView to view all the data.
Inside my ListView I also have a TextView with the text "Like" in it. Now when I click the like text it will change to "Liked" and I'm updating my like status in my database.
Now my problem is that when i click the "Like" text, the text changes to "Liked" and also it is updated in DB. But also when I scroll through the List View, I can notice other lists' Like text is also changed to Liked. I'm not sure what's going wrong.
I've been trying to get around this problem for quite some days but had no success.
This is my adapter code. At the bottom you can see my onClickListener for the textview
package com.mytestapp.myapp;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ForumAdapter extends ArrayAdapter<DiscussionList> {
private static List<DiscussionList> items = null;
public ForumAdapter(Context context, List<DiscussionList> items) {
super(context, R.layout.custom_list, items);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
public static DiscussionList getModelPosition(int position) {
return items.get(position);
}
public void refill(List<DiscussionList> items) {
items.clear();
items.addAll(items);
notifyDataSetChanged();
}
public static class ViewHolder {
WebView mywebviewholder;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View v = convertView;
if (v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.custom_list, null);
} else {
holder = (ViewHolder) convertView.getTag();
}
DiscussionList app = items.get(position);
if (app != null) {
TextView titleText = (TextView) v.findViewById(R.id.dscTitle);
TextView categoryText = (TextView) v.findViewById(R.id.dscCategory);
TextView descriptionText = (TextView) v
.findViewById(R.id.dscDescription);
TextView timeText = (TextView) v.findViewById(R.id.dscTime);
TextView idText = (TextView) v.findViewById(R.id.dscDiscId);
final TextView likeText = (TextView) v.findViewById(R.id.likeText1);
String like_Status = app.getLikeStatus();
titleText.setText(app.getTitle());
categoryText.setText(app.getCategory());
descriptionText.setText(app.getDescription());
timeText.setText(app.getTime());
idText.setText(app.getDiscId());
if (like_Status == "null") {
likeText.setText("Like");
} else {
likeText.setText("Liked");
}
final String dId = app.getDiscId();
// onClick for image button inside list view
likeText.setTag(new Integer(position));
likeText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Integer myposition = (Integer) view.getTag();
// Toast.makeText(getContext(), "" + dId,
// Toast.LENGTH_SHORT)
// .show();
likeText.setText("Liked");
MainActivity val = new MainActivity();
val.updateLikeTable(dId);
}
});
}
return v;
}
}
And also this is my MainActivity.java file where i update the likes in database
package com.mytestapp.myapp;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity implements FetchDataListener {
public static String strTitle = "0", strCategory = "0",
strDescription = "0", strTime = "0", strDid = "0";
Collegemate_DB db = new Collegemate_DB(this);
int likeStatus = 1;
private ProgressDialog dialog;
public static String usId=null;
ImageButton imgButton;
List<DiscussionList> items = new ArrayList<DiscussionList>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_forum_topics);
usId = db.getCurrentuserId();
initView();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/*
* On click listener to get values from DiscussionList class and send it
* to another activity when clicking on the list item
*/
ListView forumList = getListView();
forumList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Get position of the clicked list item from adapter
String dTitle, dCategory, dDescription, dTime, dDid;
DiscussionList accessVar = ForumAdapter
.getModelPosition(position);
dTitle = accessVar.getTitle();
dCategory = accessVar.getCategory();
dDescription = accessVar.getDescription();
dTime = accessVar.getTime();
dDid = accessVar.getDiscId();
/*
* Storing the forum values in string and passing it to another
* activity
*/
String values[] = { dTitle, dCategory, dDescription, dTime,
dDid };
Intent i = new Intent(MainActivity.this, ForumFullView.class);
i.putExtra("sendData", values);
startActivity(i);
}
});
}
private void initView() {
// show progress dialog
Log.i("j","Inside Init");
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://example.com/mypath/listData.php?currentUser_id="
+ usId;
Log.i("Fetch Url : ", url);
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
#Override
public void onFetchComplete(List<DiscussionList> data) {
// dismiss the progress dialog
if (dialog != null)
dialog.dismiss();
// create new adapter
ListView forumList = getListView();
// set the adapter to list
ForumAdapter adapter = new ForumAdapter(this, data);
if (forumList.getAdapter() == null) {
//final ForumAdapter adapter = new ForumAdapter(this, data);
forumList.setAdapter(adapter);
} else {
((ForumAdapter) forumList.getAdapter()).refill(items);
}
// setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if (dialog != null)
dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
public void updateLikeTable(String dId,List<DiscussionList> items) {
try {
String likeUrl = "http://example.com/mypath/createlike.php?discId="
+ dId + "&userId=" + usId + "&like_status=" + likeStatus;
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(likeUrl));
client.execute(request);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Any help is appreciated.
Thanks in advance
The problem you're having is that the ListView widget recycles its views if it can. Once a view is off the screen from scrolling, it goes onto a garbage heap so that when a new view scrolls into place it can be reused, rather than requiring a fresh one to be inflated from scratch. That recycled view is the convertView parameter in the getView() method. When your ListView is first populating, convertView will always be null, since the garbage pile has nothing in it, so you're forced to inflate new views, but subsequent calls will likely have that parameter as non-null.
The practical result of this is that when a clicked view that's been set to "Liked" gets recycled, the TextView is still there and still populated with "Liked" rather than the presumed default of "Like". So if you click a view, then scroll down so it goes off the screen, it'll come back around and cause the bug you're seeing.
What you'll probably want to do to fix this is to set the text of likeText within getView() every time, based on what it is in your database. If the post has been liked, set it to "Liked", and if it hasn't, set it to "Like". It should just be one more line, assuming you have easy access to whether or not the post is liked from your DiscussionList object.
P.S. As a side note, hard-coded strings are typically frowned upon in Android, so you may want to move your "Liked" string into the resource files. It's not really necessary unless you're planning to do translations, but it's still good practice.

Listview not displaying the right image in android

In my app I have a listview. Each listview item contains an image view and several textviews. To display the image I use Drawable. But the images are displayed in the wrong row when scrolling. The image in a row changes several times until the right image appears. I have searched the web but I found nothing working for me. I am posting my code below. Please help me! Thanks in advance!
MainActivity.java
package com.makemyandroidapp.example.stacksites;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
private SitesAdapter mAdapter;
private ListView sitesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("StackSites", "OnCreate()");
setContentView(R.layout.activity_main);
//Get reference to our ListView
sitesList = (ListView)findViewById(R.id.sitesList);
//Set the click listener to launch the browser when a row is clicked.
sitesList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
String posID = mAdapter.getItem(pos).getID();
Intent i = new Intent(getApplicationContext(), PositionDesc.class);
i.putExtra("posID", posID);
startActivity(i);
}
});
/*
* If network is available download the xml from the Internet.
* If not then try to use the local file from last time.
*/
if(isNetworkAvailable()){
Log.i("StackSites", "starting download Task");
SitesDownloadTask download = new SitesDownloadTask();
download.execute();
}else{
mAdapter = new SitesAdapter(getApplicationContext(), -1, SitesXmlPullParser.getStackSitesFromFile(MainActivity.this, "StackSites.xml"));
sitesList.setAdapter(mAdapter);
}
}
//Helper method to determine if Internet connection is available.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/*
* AsyncTask that will download the xml file for us and store it locally.
* After the download is done we'll parse the local file.
*/
private class SitesDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
//Download the file
try {
Downloader.DownloadFromUrl("https://duapune.com/mobile/listaeplote.php", openFileOutput("StackSites.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
//setup our Adapter and set it to the ListView.
mAdapter = new SitesAdapter(MainActivity.this, -1, SitesXmlPullParser.getStackSitesFromFile(MainActivity.this, "StackSites.xml"));
sitesList.setAdapter(mAdapter);
Log.i("StackSites", "adapter size = "+ mAdapter.getCount());
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent objIntent = new Intent(getApplication(), TabActivity.class);
finish();
startActivity(objIntent);
}
}
SitesAdapter.java
package com.makemyandroidapp.example.stacksites;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.view.View.OnClickListener;
/*
* Custom Adapter class that is responsible for holding the list of sites after they
* get parsed out of XML and building row views to display them on the screen.
*/
public class SitesAdapter extends ArrayAdapter<StackSite> {
//ImageLoader imageLoader;
//DisplayImageOptions options;
Context c;
String url1;
String url2;
Drawable backgr;
ImageView iconImg;
int posi;
RelativeLayout row;
public SitesAdapter(Context ctx, int textViewResourceId, List<StackSite> sites) {
super(ctx, textViewResourceId, sites);
c=ctx;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent){
posi=pos;
row = (RelativeLayout)convertView;
Log.i("StackSites", "getView pos = " + pos);
if(null == row){
//No recycled View, we have to inflate one.
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.row_site, null);
}
//Get our View References
final TextView kompaniaTxt = (TextView)row.findViewById(R.id.nameTxt);
TextView pozicioniTxt = (TextView)row.findViewById(R.id.aboutTxt);
final TextView kategoriaTxt = (TextView)row.findViewById(R.id.kategoriaTxt);
TextView qytetiTxt = (TextView)row.findViewById(R.id.qytetiTxt);
//final ProgressBar indicator = (ProgressBar)row.findViewById(R.id.progress);
kompaniaTxt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//String emri_komp=kompaniaTxt.getText().toString().replaceAll("\\s+","%20");
String emri_komp=kompaniaTxt.getText().toString();
Intent intent=new Intent(c,CompanyDesc.class);
intent.putExtra("emri_komp", emri_komp);
intent.putExtra("url1", url1);
c.startActivity(intent);
}
});
kategoriaTxt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String idKateg=getItem(posi).getIdKategoria();
Intent intent=new Intent(c,CategoryList.class);
intent.putExtra("idKateg", idKateg);
intent.putExtra("url2", url2);
c.startActivity(intent);
}
});
//Set the relavent text in our TextViews
kompaniaTxt.setText(getItem(pos).getKompania());
pozicioniTxt.setText(getItem(pos).getPozicioni());
kategoriaTxt.setText(getItem(pos).getKategoria());
qytetiTxt.setText(getItem(pos).getQyteti());
url1=getItem(pos).getImgUrl();
SitesDownloadTask download=new SitesDownloadTask();
download.execute();
return row;
}
private class SitesDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
try { iconImg = (ImageView)row.findViewById(R.id.iconImg);
backgr=drawable_from_url(url1,"kot");
//backgr=drawable_from_url("https://duapune.com/photos/duapune#duapune.com1349707357.png","kot");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
iconImg.setBackground(backgr);
}
Drawable drawable_from_url(String url, String src_name) throws
java.net.MalformedURLException, java.io.IOException
{System.out.println("uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu");
return Drawable.createFromStream(((java.io.InputStream)
new java.net.URL(url.trim()).getContent()), src_name);
}
}
}
Try this..
You have to use ViewHolder for that issue
private class ViewHolder {
ImageView iconImg;
TextView kompaniaTxt,pozicioniTxt,kategoriaTxt,qytetiTxt;
}
EDIT
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = getActivity().getLayoutInflater().inflate(R.layout.row_site, parent, false);
holder = new ViewHolder();
holder.iconImg = (ImageView) view.findViewById(R.id.iconImg);
holder.kompaniaTxt = (TextView) view.findViewById(R.id.nameTxt);
holder.pozicioniTxt = (TextView) view.findViewById(R.id.aboutTxt);
//holder.kategoriaTxt = (TextView) view.findViewById(R.id.kategoriaTxt);
holder.qytetiTxt = (TextView) view.findViewById(R.id.qytetiTxt);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.kompaniaTxt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//String emri_komp=kompaniaTxt.getText().toString().replaceAll("\\s+","%20");
String emri_komp=holder.kompaniaTxt.getText().toString();
Intent intent=new Intent(c,CompanyDesc.class);
intent.putExtra("emri_komp", emri_komp);
intent.putExtra("url1", url1);
c.startActivity(intent);
}
});
holder.kategoriaTxt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String idKateg=getItem(posi).getIdKategoria();
Intent intent=new Intent(c,CategoryList.class);
intent.putExtra("idKateg", idKateg);
intent.putExtra("url2", url2);
c.startActivity(intent);
}
});
//Set the relavent text in our TextViews
holder.kompaniaTxt.setText(getItem(pos).getKompania());
holder.pozicioniTxt.setText(getItem(pos).getPozicioni());
holder.kategoriaTxt.setText(getItem(pos).getKategoria());
holder.qytetiTxt.setText(getItem(pos).getQyteti());
url1=getItem(pos).getImgUrl();
SitesDownloadTask download=new SitesDownloadTask();
download.execute();
return view;
}
and onPostExecute
#Override
protected void onPostExecute(Void result){
holder.iconImg.setBackground(backgr);
}
EDIT
Instead of using SitesDownloadTask AsyncTask use Universal Image Loader lib
https://github.com/nostra13/Android-Universal-Image-Loader
lazy image loader
https://github.com/thest1/LazyList

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