android button refresh - android

I am building a android-based app to implement twitter search function. The button click only works for the first. If i change the search term and click the button again, it fails to refresh. Anyone can give me a hint?
`public class TwitterSActivity extends Activity implements OnClickListener{
EditText etQuery;
Button btnQuery;
class Tweet{
public String username;
public String message;
public String image_url;
}
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
#Override
public void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etQuery = (EditText) findViewById (R.id.et);
btnQuery = (Button) findViewById (R.id.btn);
btnQuery.setOnClickListener(this);
}
#Override
public void onClick(View v){
if(v.getId() == R.id.btn){
Toast.makeText(this, "Query submitted", Toast.LENGTH_LONG).show();
Getdata getdata = new Getdata();
String returned = null;
String searchTerm = etQuery.getText().toString();
try {
returned = getdata.getInternetData(searchTerm);
} catch (Exception e) {
e.printStackTrace();
}
try{
JSONObject jo = new JSONObject(returned);
JSONArray ja = jo.getJSONArray("results");
for(int i=0; i<ja.length(); i++){
JSONObject job = ja.getJSONObject(i);
Tweet tt = new Tweet();
tt.username = job.getString("from_user");
tt.message = job.getString("text");
tt.image_url = job.getString("profile_image_url");
tweets.add(tt);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data: "+e.toString());
}
ListView lv = (ListView) findViewById(R.id.listView1);
class FancyAdapter extends ArrayAdapter<Tweet> {
public FancyAdapter() {
super(TwitterSActivity.this, android.R.layout.simple_list_item_1, tweets);
}
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.listitem, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
holder.populatefrom(tweets.get(position));
return(convertView);
}
class ViewHolder {
public TextView username = null;
public TextView message = null;
public ImageView image = null;
ViewHolder(View listitem){
username = (TextView)listitem.findViewById(R.id.username);
message = (TextView)listitem.findViewById(R.id.message);
image = (ImageView)listitem.findViewById(R.id.avatar);
}
void populatefrom(Tweet t){
username.setText(t.username);
message.setText(t.message);
image.setImageBitmap(getBitmap(t.image_url));
}
}
}
FancyAdapter ar = new FancyAdapter();
lv.setAdapter(ar);
}
}
public Bitmap getBitmap(String bitmapUrl) {
try {
URL url = new URL(bitmapUrl);
return BitmapFactory.decodeStream(url.openConnection().getInputStream());
}
catch(Exception e) {return null;}
}`

Finally i figure it out, here is how I fix it:
I change ArrayList<Tweet> tweets = new ArrayList<Tweet>(); to final ArrayList<Tweet> tweets = new ArrayList<Tweet>();
and then move it under onClick() method. It works well without notifyDataSetChanged().

Related

How to show only list view items which value is equal to a value in the Json

iam creating an App which should show the Sights in a Listview.
The datas are parsed from a json.
At this json there is a column which declares in which City the sight is.
Now i would like to create a kind of a filter which should check the current Cityname with the City values in my Json.
For example there is a Sight in Berlin and my current city is Berlin, the Listview should show it. If the user is in Munich and the sight is in Berlin, the listview shouldnt show this item.
I get the current cityname value from a different Activity in a TextView.
Here is my Listview Activity:
public class Locations extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = Locations.class.getSimpleName();
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
int i = 1;
private ProgressDialog pDialog;
String name;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/maptest.json";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Intent i = getIntent();
String cityname = i.getExtras().getString("cityname");
TextView city = (TextView) findViewById(R.id.ort);
city.setText(cityname);
pDialog = new ProgressDialog(Locations.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener((AdapterView.OnItemClickListener) this);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
final ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.VISIBLE);
ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setVisibility(View.VISIBLE);
filteropen.setVisibility(View.INVISIBLE);
}
});
final ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.INVISIBLE);
ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setVisibility(View.VISIBLE);
filterclose.setVisibility(View.INVISIBLE);
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try{
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
arrayList.add(new productforloc(
po.getString("imageurl"),
po.getString("name"),
po.getString("street"),
po.getString("postalcode"),
po.getString("musicstyle"),
po.getString("musicsecond"),
po.getString("entry"),
po.getString("opening"),
po.getString("agegroup"),
po.getString("urlbtn"),
po.getString("Fsk"),
po.getString("city"),
po.getString("bg")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
final CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
}
private String readURL(String url){
StringBuilder content = new StringBuilder();
try{
URL uri = new URL(url);
URLConnection urlConnection = uri.openConnection();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) !=null){
content.append(line+"\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(position);
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",pForloc.getName());
intent.putExtra("imageurl",pForloc.getImage());
intent.putExtra("street",pForloc.getStreet());
intent.putExtra("postalcode",pForloc.getPostalcode());
intent.putExtra("entry",pForloc.getEntry());
intent.putExtra("agegroup",pForloc.getAgegroup());
intent.putExtra("opening",pForloc.getOpening());
intent.putExtra("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
intent.putExtra("musicstyle",pForloc.getMusicstyle());
intent.putExtra("musicsecond",pForloc.getMusicsecond());
intent.putExtra("bg",pForloc.getBg());
startActivity(intent);
}
/**
* Async task class to get json by making HTTP call
}
*/
}
and here is my Customlistadapter Activity;
public class CustomListAdapterforloc extends ArrayAdapter<productforloc>{
ArrayList<productforloc> products;
Context context;
int resource;
public CustomListAdapterforloc(Context context, int resource, List<productforloc> products) {
super(context, resource, products);
this.products = (ArrayList<productforloc>) products;
this.context = context;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView== null){
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.model,null,true);
}
productforloc product = getItem(position);
ImageView imageView = (ImageView) convertView.findViewById(R.id.imagelist);
Picasso.with(context).load(product.getImage()).into(imageView);
TextView txtName= (TextView) convertView.findViewById(R.id.namelist);
txtName.setText(product.getName());
return convertView;
}
}
Get current city name from intent.
String currentCityName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Intent i = getIntent();
currentCityName = i.getExtras().getString("cityname");
...........
.................
}
Add condition to match cityName with currentCityName before adding productforloc object to ArrayList:
try {
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
String cityName = po.getString("city");
if(!cityName.equals(currentCityName)) {
arrayList.add(new productforloc(
po.getString("imageurl"),
po.getString("name"),
po.getString("street"),
po.getString("postalcode"),
po.getString("musicstyle"),
po.getString("musicsecond"),
po.getString("entry"),
po.getString("opening"),
po.getString("agegroup"),
po.getString("urlbtn"),
po.getString("Fsk"),
po.getString("city"),
po.getString("bg")));
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Android Populate Listview from JSON (link from edittext)

I am new in android and am working with a project that loads data from internet into listview. I got my prototype here: kaleidosblog.com/android-listview-load-data-from-json
So these will be the json links:
http://www.funtrial.com/christiancepe/announcements/json.php?page=1
http://www.funtrial.com/christiancepe/announcements/json.php?page=2
So on..
In my activity, I have my EditText, Button and ListView.
Editext will get the url.
Button will be use to load the json link (from url) to listview
Listview will display datas
In my current program, it only works on first click of button. So once I entered the first json, it will show the correct data. But when I try to change the json on EditText, still the ListView is populated by the first json. In short, my ListView does not refresh everytime I am changing the link and clicking the button.
What's wrong with this?
Main Activity:
protected void onCreate(Bundle savedInstanceState) {
final Button searchButton = (Button) findViewById(R.id.searchButton);
final EditText searchForm = (EditText) findViewById(R.id.searchForm);
searchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
list = (ListView) findViewById(R.id.list);
adapter = new ListAdapter(MainActivity.this);
list.setAdapter(adapter);
search = searchForm.getText().toString();
Download_data download_data = new Download_data((download_complete) MainActivity.this);
download_data.download_data_from_link(search);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), search, Toast.LENGTH_LONG).show();
}
});
}
public void get_data(String data){
try {
JSONObject jsonObj = new JSONObject(data);
JSONArray data_array = jsonObj.getJSONArray("announcements");
for (int i = 0 ; i < data_array.length() ; i++)
{
JSONObject obj=new JSONObject(data_array.get(i).toString());
Countries add=new Countries();
add.name = obj.getString("message");
add.code = obj.getString("date");
countries.add(add);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
Download_data.java
public class Download_data implements Runnable {
public download_complete caller;
public interface download_complete{
public void get_data(String data);
}
Download_data(download_complete caller) {
this.caller = caller;
}
private String link;
public void download_data_from_link(String link){
this.link = link;
Thread t = new Thread(this);
t.start();
}
public void run() {
threadMsg(download(this.link));
}
private void threadMsg(String msg) {
if (!msg.equals(null) && !msg.equals("")) {
Message msgObj = handler.obtainMessage();
Bundle b = new Bundle();
b.putString("message", msg);
msgObj.setData(b);
handler.sendMessage(msgObj);
}
}
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String Response = msg.getData().getString("message");
caller.get_data(Response);
}
};
public static String download(String url) {
URL website;
StringBuilder response = null;
try {
website = new URL(url);
HttpURLConnection connection = (HttpURLConnection) website.openConnection();
connection.setRequestProperty("charset", "utf-8");
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
} catch (Exception e) {
return "";
}
return response.toString();
}
ListAdapter.java
MainActivity main;
ListAdapter(MainActivity main)
{
this.main = main;
}
#Override
public int getCount() {
return main.countries.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
static class ViewHolderItem {
TextView name;
TextView code;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolderItem holder = new ViewHolderItem();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) main.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cell, null);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.code = (TextView) convertView.findViewById(R.id.code);
convertView.setTag(holder);
}
else
{
holder = (ViewHolderItem) convertView.getTag();
}
holder.name.setText(this.main.countries.get(position).name);
holder.code.setText(this.main.countries.get(position).code);
return convertView;
}
It appears that the countries list is being added to each time in get_data(), but never cleared out. At the start of get_data, you most likely want to clear the countries list with the following call:
countries.clear();
Then the data in the countries list will be cleared out, the new downloaded data will be added to the countries list, and then updated in the view when the adapter is notified of the data change.

How to Merge two or more adapters and show in one ListView in Android

I have to ListView custom adapters returning both Twitter and Facebook feeds. Also they do have their own XML. Till now I was showing them in separate Activity, now I am planning to combine both data and show in one adapter. I heard there is some concept like "Merge Adapters". Can someone help me with below posted code ?
File : FacebookAdapter.java :
public class FacebookAdapter extends ArrayAdapter<RssFeedStructure> {
List<RssFeedStructure> imageAndTexts1 = null;
public FacebookAdapter(Activity activity,
List<RssFeedStructure> imageAndTexts) {
super(activity, 0, imageAndTexts);
imageAndTexts1 = imageAndTexts;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Activity activity = (Activity) getContext();
LayoutInflater inflater = activity.getLayoutInflater();
View rowView = inflater.inflate(R.layout.facebookadapter, null);
TextView textView = (TextView) rowView.findViewById(R.id.feed_text);
TextView timeFeedText = (TextView) rowView
.findViewById(R.id.feed_updatetime);
ImageView imageView = (ImageView) rowView.findViewById(R.id.feed_image);
try {
Log.d("rssfeed", "imageAndTexts1.get(position).getImgLink() :: "
+ imageAndTexts1.get(position).getImgLink() + " :: "
+ imageAndTexts1.get(position).getTitle());
textView.setText(imageAndTexts1.get(position).getDescription());
SpannableString content = new SpannableString(imageAndTexts1.get(
position).getPubDate());
content.setSpan(new UnderlineSpan(), 0, 13, 0);
timeFeedText.setText(content);
if (imageAndTexts1.get(position).getImgLink() != null) {
URL feedImage = new URL(imageAndTexts1.get(position)
.getImgLink().toString());
if (!feedImage.toString().equalsIgnoreCase("null")) {
HttpURLConnection conn = (HttpURLConnection) feedImage
.openConnection();
InputStream is = conn.getInputStream();
Bitmap img = BitmapFactory.decodeStream(is);
imageView.setImageBitmap(img);
} else {
imageView.setBackgroundResource(R.drawable.rss_tab_tweets);
}
}
} catch (MalformedURLException e) {
} catch (IOException e) {
}
return rowView;
}
}
File : FacebookActivity.java :
public class FacebookFeeds extends Activity {
/** Called when the activity is first created. */
ListView _rssFeedListView;
List<JSONObject> jobs;
List<RssFeedStructure> rssStr;
private FacebookAdapter _adapter;
String sorti = "";
String mode = "";
//Button sort_Btn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
_rssFeedListView = (ListView) findViewById(R.id.rssfeed_listview);
RssFeedTask rssTask = new RssFeedTask();
rssTask.execute();
}
private class RssFeedTask extends AsyncTask<String, Void, String> {
// private String Content;
private ProgressDialog Dialog;
String response = "";
#Override
protected void onPreExecute() {
Dialog = new ProgressDialog(FacebookFeeds.this);
Dialog.setMessage("Rss Loading...");
Dialog.show();
}
#Override
protected String doInBackground(String... urls) {
try {
String feed = "https://someurl";
XmlHandler rh = new XmlHandler();
rssStr = rh.getLatestArticles(feed);
} catch (Exception e) {
}
return response;
}
#Override
protected void onPostExecute(String result) {
if (rssStr != null) {
_adapter = new FacebookAdapter(FacebookFeeds.this, rssStr);
_rssFeedListView.setAdapter(_adapter);
}
Dialog.dismiss();
}
}
}
File : TwitterAdapter.java :
public class TwitterAdapter extends ArrayAdapter<RssFeedStructure> {
List<RssFeedStructure> imageAndTexts1 = null;
public TwitterAdapter(Activity activity,
List<RssFeedStructure> imageAndTexts) {
super(activity, 0, imageAndTexts);
imageAndTexts1 = imageAndTexts;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Activity activity = (Activity) getContext();
LayoutInflater inflater = activity.getLayoutInflater();
View rowView = inflater.inflate(R.layout.twitteradapter, null);
TextView textView = (TextView) rowView.findViewById(R.id.feed_text);
TextView timeFeedText = (TextView) rowView
.findViewById(R.id.feed_updatetime);
ImageView imageView = (ImageView) rowView.findViewById(R.id.feed_image);
try {
Log.d("rssfeed", "imageAndTexts1.get(position).getImgLink() :: "
+ imageAndTexts1.get(position).getImgLink() + " :: "
+ imageAndTexts1.get(position).getTitle());
textView.setText(imageAndTexts1.get(position).getTitle());
SpannableString content = new SpannableString(imageAndTexts1.get(
position).getPubDate());
content.setSpan(new UnderlineSpan(), 0, 13, 0);
timeFeedText.setText(content);
if (imageAndTexts1.get(position).getImgLink() != null) {
URL feedImage = new URL(imageAndTexts1.get(position)
.getImgLink().toString());
if (!feedImage.toString().equalsIgnoreCase("null")) {
HttpURLConnection conn = (HttpURLConnection) feedImage
.openConnection();
InputStream is = conn.getInputStream();
Bitmap img = BitmapFactory.decodeStream(is);
imageView.setImageBitmap(img);
} else {
imageView.setBackgroundResource(R.drawable.rss_tab_tweets);
}
}
} catch (MalformedURLException e) {
} catch (IOException e) {
}
return rowView;
}
}
File : TwitterActivity.java :
public class TwitterFeeds extends Activity {
/** Called when the activity is first created. */
ListView _rssFeedListView;
List<JSONObject> jobs;
List<RssFeedStructure> rssStr;
private TwitterAdapter _adapter;
String sorti = "";
String mode = "";
//Button sort_Btn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
_rssFeedListView = (ListView) findViewById(R.id.rssfeed_listview);
RssFeedTask rssTask = new RssFeedTask();
rssTask.execute();
}
private class RssFeedTask extends AsyncTask<String, Void, String> {
// private String Content;
private ProgressDialog Dialog;
String response = "";
#Override
protected void onPreExecute() {
Dialog = new ProgressDialog(TwitterFeeds.this);
Dialog.setMessage("Rss Loading...");
Dialog.show();
}
#Override
protected String doInBackground(String... urls) {
try {
String feed = "https://someurl";
XmlHandler rh = new XmlHandler();
rssStr = rh.getLatestArticles(feed);
} catch (Exception e) {
}
return response;
}
#Override
protected void onPostExecute(String result) {
if (rssStr != null) {
_adapter = new TwitterAdapter(TwitterFeeds.this,
rssStr);
_rssFeedListView.setAdapter(_adapter);
}
Dialog.dismiss();
}
}
}
Maybe this MergeAdapter can help you : https://github.com/commonsguy/cwac-merge
Make a new adapter something like FacebookTwitterAdapter, probably taking both adapters as constructor parameters.
getViewTypeCount - Return 2 (either facebook or twitter view)
getItemViewType - Return 0 for facebook view and 1 for twitter view
getView - Return either the facebook or twitter view depending on how you want to display the views maybe by timeline?
The easiest option might be to create one giant arraylist of items, and populating it over a single listview, maybe you could assign section breaks in between in the listview and maybe you can design custom layouts to differentiate facebook and twitter layouts. OR you can use "mergeadapter" by "commonsware" in "github".

pass data to new activity from adapter class

I made one custom listview with image and text.When u click on image it ll lead you to new activity.Now i want to pass image and text to new activity.i know with putExtra method you can pass data but i don't know how can i use it here..
thanks in advance...
here is my code for adapter class..
Note..I am parsing data from json
Onclick method is used to go on another activity...
public class Adapter extends BaseAdapter {
private static final String TAG = "Adapter";
private Activity mActivity;
public ArrayList<Data> mObjects;
// /private final Context context;
Context context;
static class ViewHolder {
static ImageView icon;
TextView title;
TextView name;
TextView review;
DownloadImageTask mTask;
String ab[];
// DownloadImageTask1 mTask1;
// ImageView photo;
}
public Adapter(Activity activity, Context context, ArrayList<Data> mObjects) {
this.mActivity = (Activity) activity;
this.context = context;
this.mObjects = mObjects;
}
public void setObjects(ArrayList<Data> mObjects) {
this.mObjects = mObjects;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Data item = mObjects.get(position);
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = mActivity.getLayoutInflater();
rowView = inflater.inflate(R.layout.item, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.icon = (ImageView) rowView.findViewById(R.id.image);
// viewHolder.photo = (ImageView) rowView.findViewById(R.id.photo);
viewHolder.title = (TextView) rowView.findViewById(R.id.title);
viewHolder.name = (TextView) rowView.findViewById(R.id.name);
viewHolder.review = (TextView) rowView.findViewById(R.id.status);
rowView.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) rowView.getTag();
holder.title.setText(item.getmTitle());
holder.name.setText(item.getmConcatinate());
holder.review.setText(item.getmreview());
holder.icon.setBackgroundResource(R.drawable.ic_ab);
// holder.photo.setBackgroundResource(0);
holder.mTask = new DownloadImageTask(item.getmImageUrl(), holder.icon);
if (!holder.mTask.isCancelled()) {
holder.mTask.execute();
}
ViewHolder.icon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Parsing JSON Data", "Before user try122222"); // perform
// action
Intent intent = new Intent(v.getContext(), LargeView.class);
v.getContext().startActivity(intent);
}
});
// holder.mTask1 = new DownloadImageTask1(item.getmImageUrl1(),
// holder.photo);
// if (!holder.mTask1.isCancelled()) {
// holder.mTask1.execute();
// }
return rowView;
}
#Override
public int getCount() {
return (this.mObjects.size());
}
#Override
public Object getItem(int position) {
return (this.mObjects.get(position));
}
#Override
public long getItemId(int position) {
return (position);
}
public AbsListView.RecyclerListener mRecyclerListener = new RecyclerListener() {
public void onMovedToScrapHeap(View view) {
ViewHolder viewHolder = (ViewHolder) view.getTag();
DownloadImageTask imagetask = viewHolder.mTask;
// DownloadImageTask1 imagetask1 = viewHolder.mTask1;
if (imagetask != null) {
imagetask.cancel(true);
}
// if (imagetask1 != null) {
// // imagetask1.cancel(true);
// }
}
};
code in main activity.class
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile3);
name = (TextView) findViewById(R.id.textView1);
bmImage2 = (ImageView) findViewById(R.id.imageView1);
address = (TextView) findViewById(R.id.textView2);
gender = (TextView) findViewById(R.id.textView3);
loyalitypoints = (TextView) findViewById(R.id.textView7);
followers = (TextView) findViewById(R.id.textView8);
following = (TextView) findViewById(R.id.textView9);
// list13 = new ArrayList<HashMap<String, Object>>();
mListView = (ListView) findViewById(android.R.id.list);
mListView.setClickable(true);
// mListView=(ListView)findViewById(R.id.list);
mAdapter = new Adapter(this,c,mSource );
mListView.setAdapter(mAdapter);
Log.w("Parsing JSON Data", "Before Item click");
mListView.setRecyclerListener(mAdapter.mRecyclerListener);
}
public String getJSONfromURL(String url) {
InputStream is = null;
String result = "";
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
use this way:
ViewHolder.icon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Parsing JSON Data", "Before user try122222"); // perform
// action
Intent intent = new Intent(context, LargeView.class);
intent.putExtra("name", "dhaval");
context.startActivity(intent);
}
});
pass image in intent is BAD idea. just pass URL, Image Path, image name whatever you have..
like:
Intent intent = new Intent(context, LargeView.class);
intent.putExtra("name", "dhaval");
intent.putExtra("imangeUTL", "www.xyz.com/images/test.png");
context.startActivity(intent);

how to display custom listview using list fragments in android

I have divided my android screen into 2 fragements .In the first one I make a listview from server database to android mobile.The problem is that I can't call getview method in the base adapter class. Do help me out
public class MyListFragment1 extends ListFragment {
ImageView back;
String url = Main.url;
String Qrimage;
Bitmap bmp;
ListView list ;
AppetiserFragment adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.applistviewfragment, container, false);
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// back=(ImageView)findViewById(R.id.backfoodmenu);
/*
* back.setOnClickListener(new OnClickListener() {
*
* public void onClick(View v) { // TODO Auto-generated method stub
* Intent intent=new Intent(getApplicationContext(),FoodMenu.class);
* intent.putExtra("url", url); startActivity(intent); } });
*/
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
InputStream is = null;
String result = "";
JSONObject jArray = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url + "test.php3");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
// TODO: handle exception
Log.e("Log", "Error in Connection" + e.toString());
// Intent intent = new Intent(ViewQRCode.this, PimCarder.class);
// startActivity(intent);
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
jArray = new JSONObject(result);
JSONArray json = jArray.getJSONArray("appetiser");
Context context = null;
context = this.getActivity().getApplicationContext();
//(Here i want give lisid from xml)
list=(Listview)findViewById(R.id.list);//i type here it shows an error
adapter = new AppetiserFragment(context, json);
context = getActivity().getApplicationContext();
list.setAdapter(adapter);
} catch (Exception e) {
// TODO: handle exception
Log.e("log", "Error in Passing data" + e.toString());
}
}
}
AppetiserFragment.java
public class AppetiserFragment extends BaseAdapter {
String url = Main.url;
public Context Context;
String qrimage;
Bitmap bmp, resizedbitmap;
Bitmap[] bmps;
Activity activity = null;
private LayoutInflater inflater;
private ImageView[] mImages;
String[] itemimage;
TextView[] tv;
String itemname, price, desc, itemno;
String[] itemnames, checkeditems, itemnos;
String[] prices;
String[] descs;
HashMap<String, String> map = new HashMap<String, String>();
public AppetiserFragment(Context context, JSONArray imageArrayJson) {
Context = context;
// inflater =
System.out.println(imageArrayJson);
// (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(activity);
inflater = LayoutInflater.from(context);
this.mImages = new ImageView[imageArrayJson.length()];
this.bmps = new Bitmap[imageArrayJson.length()];
this.itemnames = new String[imageArrayJson.length()];
this.prices = new String[imageArrayJson.length()];
this.descs = new String[imageArrayJson.length()];
this.itemnos = new String[imageArrayJson.length()];
try {
for (int i = 0; i < imageArrayJson.length(); i++) {
JSONObject image = imageArrayJson.getJSONObject(i);
qrimage = image.getString("itemimage");
itemname = image.getString("itemname");
itemno = new Integer(i + 1).toString();
price = image.getString("price");
desc = image.getString("itemdesc");
System.out.println(price);//here i can print price
itemnames[i] = itemname;
prices[i] = price;
descs[i] = desc;
itemnos[i] = itemno;
byte[] qrimageBytes = Base64.decode(qrimage.getBytes());
bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
qrimageBytes.length);
int width = 100;
int height = 100;
resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
true);
bmps[i] = bmp;
mImages[i] = new ImageView(context);
mImages[i].setImageBitmap(resizedbitmap);
mImages[i].setScaleType(ImageView.ScaleType.FIT_START);
// tv[i].setText(itemname);
}
System.out.println(map);
} catch (Exception e) {
// TODO: handle exception
}
}
public AppetiserFragment() {
// TODO Auto-generated constructor stub
}
public int getCount() {
return mImages.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder viewHolder;
if (view == null) {
view = inflater.inflate(R.layout.appetiserlistview, null);
System.out.println("prakash");
viewHolder = new ViewHolder();
viewHolder.image = (ImageView) view
.findViewById(R.id.appetiserimage);
viewHolder.text = (TextView) view.findViewById(R.id.appetisertext);
viewHolder.desc = (TextView) view.findViewById(R.id.appetiserdesc);
viewHolder.price = (TextView) view
.findViewById(R.id.appetiserprice);
viewHolder.appitemnum = (TextView) view
.findViewById(R.id.appitemno);
// viewHolder.checkbox = (CheckBox) view.findViewById(R.id.bcheck);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.image.setImageBitmap(bmps[position]);
viewHolder.appitemnum.setText(itemnos[position]);
viewHolder.price.setText(prices[position]);
viewHolder.desc.setText(descs[position]);
// viewHolder.checkbox.setTag(itemnames[position]);
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(itemnames[position]);
return view;
}
static class ViewHolder {
protected TextView text, price, desc, appitemnum;
protected ImageView image;
}
}
i can able to print json data in base adpater class . Now i want pass json data in to text,image. i thought getview method is not calling . please help me
You can also user ListActivity instead of ListFragment.
It will behave like normal activity and you can find all the list related methods easily.
like this..,
public class MainActivity extends ListActivity {
oncreate() {
** code
ListView list = getListView();
**code
}
}
I think as you are using the custom list with you id "R.id.list" so no need to extend your fragment with listFragment extend with Fragment only.
other wise if you want use the listFragment then use like in XML
<ListView android:id="#id/android:list" android:layout_height="fill_parent"
android:layout_width="fill_parent" android:layout_weight="1.0"
android:layout_marginTop="2dip" android:scrollingCache="false"
android:clickable="true" android:cacheColorHint="#00000000"
android:focusable="true"
android:background="#drawable/listfocused"
android:dividerHeight="1dip" xmlns:android="http://schemas.android.com/apk/res/android"/>
in java get list as
ListView list = this.getListView();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
...
list=(Listview)findViewById(R.id.list);//i type here it shows an error
...
}
This is because you are trying to find the views in the onCreate() method; at this point of time, the fragment's layout has not yet been inflated, hence all findViewById() calls will return null.
You can only find the view after the layout is inflated, which is in onCreateView(). So override the onCreateView() method and call findViewById() and set the list's adapter there!

Categories

Resources