I am using EndlessAdapter to display a list of images, but the new list not adding after the scrolling.
My code is like this:
/***
Copyright (c) 2008-2009 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.sample.endlessdemo;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.ListActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
public class EndlessAdapterDemo extends ListActivity {
String name[];
String urls[];
int j,limit;
//ListView listValues;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
RestClient post=new RestClient("http://iconnect.myappdemo.com/listusers.php");
try {
post.ExecutePost();
} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String response=post.getResponse();
Log.e("Respopnse :",response);
JSONArray json = null;
try {
json = new JSONArray(response);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
name=new String[json.length()];
for(int i=0;i<json.length();i++)
try {
name[i]=json.getJSONObject(i).getString("picture").toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
urls=new String[10];
for (int i=0;i<10;i++) { urls[i]=name[i]; }
setListAdapter(new DemoAdapter(urls));
}
class DemoAdapter extends EndlessAdapter {
private RotateAnimation rotate=null;
DemoAdapter(String list[]) {
super(new StartingView(EndlessAdapterDemo.this,R.layout.row,list));
rotate=new RotateAnimation(0f,360f,Animation.RELATIVE_TO_SELF,0.5f, Animation.RELATIVE_TO_SELF,0.5f);
rotate.setDuration(1000);
rotate.setRepeatMode(Animation.RESTART);
rotate.setRepeatCount(Animation.INFINITE);
}
#Override
protected View getPendingView(ViewGroup parent) {
Log.e("Demo Adapter","getPendingView");
View row=getLayoutInflater().inflate(R.layout.listrow,null);
View child=row.findViewById(android.R.id.list);
//View child=row.findViewById(R.id.image);
child.setVisibility(View.GONE);
child=row.findViewById(R.id.throbber);
child.setVisibility(View.VISIBLE);
child.startAnimation(rotate);
return(row);
}
#Override
protected boolean cacheInBackground() {
SystemClock.sleep(10000); // pretend to do work
Log.e("Demo Adapter","In cacheInBackground");
return(getWrappedAdapter().getCount()<20);
}
#Override
protected void appendCachedData()
{
// if (getWrappedAdapter().getCount()<75) {
// Log.e("Demo Adapter","In appendCachedData");
// #SuppressWarnings("unchecked")
// ArrayAdapter<String> a=(ArrayAdapter<String>)getWrappedAdapter();
// for (int i=0;i<5;i++) { a.add(name[a.getCount()]); }
// }
#SuppressWarnings("unchecked")
ArrayAdapter<String> a=(ArrayAdapter<String>)getWrappedAdapter();
for(int i=0;i<5;i++){
Log.e("a.getCount()+i value :",String.valueOf(a.getCount()+i));
a.getView(a.getCount()+i,null,null);
}
}
}
class StartingView extends ArrayAdapter<String>{
String startUrls[];
public StartingView(Context context, int ResourceId,String[] objects) {
super(context, ResourceId, objects);
startUrls=new String[objects.length];
startUrls=objects;
// TODO Auto-generated constructor stub
}
public View getView(int pos,View counterview,ViewGroup parent){
View row=getLayoutInflater().inflate(R.layout.row,null);
ImageView image=(ImageView)row.findViewById(R.id.image);
Log.e("position :",String.valueOf(pos));
image.setImageBitmap(convertImage(name[pos]));
return row;
}
}
public Bitmap convertImage(String imgstr){
URL aURL = null;
try {
final String imageUrl =imgstr.replaceAll(" ","%20");
Log.e("Image Url",imageUrl);
aURL = new URL(imageUrl);
URLConnection conn = aURL.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
is.close();
return bm;
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
I hope the following code will help you.
PS: The original source code and question can be found here.
public class Test extends ListActivity
implements OnScrollListener {
Aleph0 adapter = new Aleph0();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(adapter);
getListView().setOnScrollListener(this);
}
public void onScroll(AbsListView view,
int firstVisible, int visibleCount, int totalCount) {
boolean loadMore = /* maybe add a padding */
firstVisible + visibleCount >= totalCount;
if(loadMore) {
adapter.count += visibleCount; // or any other amount
adapter.notifyDataSetChanged();
}
}
public void onScrollStateChanged(AbsListView v,
int s) { }
class Aleph0 extends BaseAdapter {
int count = 40; /* starting amount */
public int getCount() { return count; }
public Object getItem(int pos) { return pos; }
public long getItemId(int pos) { return pos; }
public View getView(int pos, View v, ViewGroup p) {
TextView view = new TextView(Test.this);
view.setText("entry " + pos);
return view;
}
} }
Add this after finish loading:
StartingView.notifyDataSetChanged()
Related
i want add clickable link in android listview item, i have 5 item in each row of listview and i want only two item make clickable and open sholud in webview using putextras() intents i am using custom adapter pls any one hlep me.
suppose "link 1" is: "view Proofing"(proofinglink) (in textview) and "link 2" is : "Get More Detail"(sitelink) i want when i click link 1 then it should open in webview behind his own given url . and when i click on link 2: it should also open in webview in his own given url. using putextras() intents
here is my code.
package tipster;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import newsletter.Latest_list;
import newsletter.Webview_news;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.example.newapp.R;
public class Tipster extends Activity {
ListView lv;
ArrayList<Tipster_list>listitem;
String title;
String serviceUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tipster);
if (isNetworkAvailable()) {
// Execution here
// Toast.makeText(this, "Network is Available!",
Toast.LENGTH_LONG).show();
execute();
title="Free Tip - Betfans";
lv=(ListView) findViewById(R.id.listView_tipsterID);
listitem=new ArrayList<Tipster_list>();
}
else {
Toast.makeText(this, "Network is unavailable!",
Toast.LENGTH_LONG).show();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void execute() {
serviceUrl ="http://mobile.betfan.com/api/?
Action=top&type=default&key=MEu07MgiuWgXwJOo7Oe1aHL0yM8VvP";
//Toast.makeText(LatestNews.this, serviceUrl, Toast.LENGTH_LONG).show();
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(Tipster.this, "Please
while wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
JSONObject jsonObject = new JSONObject();
String dataString = jsonObject.toString();
InputStream is = null;
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", dataString));
String result = null;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet();
URI apiurl = new URI(serviceUrl);
httpRequest.setURI(apiurl);
HttpResponse response = httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new
InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result){
String s = result.trim();
loadingDialog.dismiss();
JSONObject respObject;
try {
respObject = new JSONObject(s);
String active = respObject.getString("status_message");
if(active.equalsIgnoreCase("success")){
JSONArray array =
respObject.getJSONArray("response");
for (int i =0; i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
String icon= jsonObject.getString("image");
String name = jsonObject.getString("name");
String total = jsonObject.getString("total");
String proofinglink =
jsonObject.getString("proofinglink");
String sitelink = jsonObject.getString("sitelink");
listitem.add(new
Tipster_list(icon,name,"+"+total,proofinglink,sitelink));
}
lv.setAdapter(new Tipster_adapter(Tipster.this,
listitem));
}else {
Toast.makeText(Tipster.this, "services received
Fail", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String getName=listitem.get(arg2).getName();
String
getproofing=listitem.get(arg2).getProofinglink();
String getsite=listitem.get(arg2).getSitelink();
Intent intent = new Intent(getApplicationContext(),
Tipster_webview.class);
intent.putExtra("gettproofing_URl",getproofing);
intent.putExtra("getsiteURL",getsite);
startActivity(intent);
}
});
}
}
LoginAsync la = new LoginAsync();
la.execute();
}
i want "proofinglink" and "sitelink" should be clickable and open in webview
here is custom adapter
public class Tipster_adapter extends BaseAdapter {
Context context;
ArrayList<Tipster_list>tipslist;
public Tipster_adapter(Context context,
ArrayList<Tipster_list> tipslist) {
super();
this.context = context;
this.tipslist = tipslist;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return tipslist.size();
}
#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;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater inflater=(LayoutInflater)
context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.activity_tipster_adapter
,null);
ImageView icon=
(ImageView)convertView.findViewById(R.id.icon_tipsterIconID);
TextView name=(TextView)
convertView.findViewById(R.id.txt_name_tipsterID);
TextView total=(TextView)
convertView.findViewById(R.id.txt_total_tipsterID);
TextView proofingLink=(TextView)
convertView.findViewById(R.id.txt_proofinglink_tipsterID);
TextView siteLink=(TextView)
convertView.findViewById(R.id.txt_sitelink_tipsterID);
Tipster_list services=tipslist.get(position);
Picasso.with(context).load(services.getImage()).into(icon);
Log.d("Url",services.getImage());
name.setText(services.getName());
total.setText(services.getTotal());
proofingLink.setText(services.getProofinglink());
siteLink.setText(services.getSitelink());
}
return convertView;
}
}
your code is ok you need to add a listener in your adapter for the view on which you want to fire an intent for example
inside your adapter getview method paste this code like this
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Tipster_list services=tipslist.get(position);
if(services!=null){
LayoutInflater inflater=(LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.activity_custom_adapter,null);
ImageView icon=(ImageView)convertView.findViewById(R.id.icon_tipsterIconID);
TextView name=(TextView) convertView.findViewById(R.id.txt_name_tipsterID);
TextView total=(TextView) convertView.findViewById(R.id.txt_total_tipsterID);
TextView proofingLink=(TextView) convertView.findViewById(R.id.txt_proofinglink_tipsterID);
TextView siteLink=(TextView) convertView.findViewById(R.id.txt_sitelink_tipsterID);
Picasso.with(context).load(services.getImage()).into(icon);
Log.d("Url",services.getImage());
name.setText(services.getName());
total.setText(services.getTotal());
proofingLink.setText(services.getProofinglink());
siteLink.setText(services.getSitelink());
convertView.setTag(position);
String getName=services.getName();
final String getproofing=services.getProofinglink();
final String getsite=services.getSitelink();
proofingLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, Tipster_webview.class);
intent.putExtra("gettproofing_URl",getproofing);
context.startActivity(intent);
}
});
siteLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, Tipster_webview.class);
intent.putExtra("site",getsite);
context.startActivity(intent);
}
});
}
return convertView;
}
TextView proofingLink=(TextView) convertView.findViewById(R.id.txt_proofinglink_tipsterID);
proofingLink.setOnClickListener(new OnItemClickListener() {
#Override
public void onClick(View arg0) {
String url = services.getProofinglink();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
TextView proofingLink=(TextView)
convertView.findViewById(R.id.txt_proofinglink_tipsterID);
proofingLink.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
TextView siteLink=(TextView)
convertView.findViewById(R.id.txt_sitelink_tipsterID);
siteLink.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
I am developing a MovieApp which loads movie posters in MainActivity Fragment using AsyncTask background thread. I am using gridview and BaseAdapter to display images. Following is the code.
MainActivityFragment.java :
package com.android.example.cinemaapp.app;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
public class MainActivityFragment extends Fragment{
MoviePosterAdapter moviePosterAdapter;
GridView posterGridView;
public HashMap<String, JSONObject> movieMap;
public MainActivityFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onStart(){
super.onStart();
updateMovies();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.moviefragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
updateMovies();
}
return super.onOptionsItemSelected(item);
}
public void updateMovies(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String sortBy = sharedPreferences.getString(getString(R.string.pref_sort_key), getString(R.string.pref_sort_popular));
new FetchMoviePosterTask().execute(sortBy);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
moviePosterAdapter = new MoviePosterAdapter(getActivity());
posterGridView = (GridView) rootView.findViewById(R.id.gridview_movie);
posterGridView.setAdapter(moviePosterAdapter);
posterGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// logic to start detail activity
startActivity(intent);
}
});
return rootView;
}
public class FetchMoviePosterTask extends AsyncTask<String, String, Void> implements Serializable {
#Override
protected Void doInBackground(String... params) {
Log.v("FetchMoviePosterTask", "In background method");
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String movieJsonStr;
try {
//logic to create uri builder
URL url = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
movieJsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
movieJsonStr = null;
}
movieJsonStr = buffer.toString();
// Log.v("MainActivityFragment", "Movie json "+movieJsonStr);
try {
String[] posterPaths = getPosterPaths(movieJsonStr);
for(String path : posterPaths){
publishProgress(path);
}
}catch(JSONException je){
Log.e("MoviePosterPath","Error while parsing JSON");
}
} catch (IOException e) {
Log.e("MoviePosterAdapter", "Error ", e);
movieJsonStr = null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MoviePosterAdapter", "Error closing stream", e);
}
}
}
return null;
}
public String[] getPosterPaths(String movieJsonStr) throws JSONException{
final String POSTER_PATH = //some value
final String POSTER_SIZE = //some value
JSONObject jsonObject = new JSONObject(movieJsonStr);
JSONArray results = jsonObject.getJSONArray("results");
String[] posterStrs = new String[results.length()];
movieMap = new HashMap<String, JSONObject>();
for(int i =0; i < results.length(); i++){
JSONObject movieObj = (JSONObject) results.get(i);
posterStrs[i] = POSTER_PATH + POSTER_SIZE + movieObj.getString("poster_path");
movieMap.put(posterStrs[i], movieObj);
}
return posterStrs;
}
#Override
protected void onProgressUpdate(String... posterValues){
Log.v("FetchMoviePosterTask", "In onProgress method");
moviePosterAdapter.add(posterValues[0]);
super.onProgressUpdate(posterValues);
}
#Override
protected void onPostExecute(Void result) {
Log.v("FetchMoviePosterTask", "In onPostExecute method");
moviePosterAdapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
}
MoviePosterAdapter.java :
package com.android.example.cinemaapp.app;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class MoviePosterAdapter extends BaseAdapter {
ArrayList<String> movieArray = new ArrayList<String>();
private Context mContext;
public MoviePosterAdapter(Context c) {
mContext = c;
}
void add(String path){
movieArray.add(path);
}
void clear(){
movieArray.clear();
}
void remove(int index){
movieArray.remove(index);
}
#Override
public int getCount() {
return movieArray.size();
}
#Override
public Object getItem(int position) {
return movieArray.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
} else {
imageView = (ImageView) convertView;
}
Picasso.with(mContext).load(movieArray.get(position)).into(imageView);
return imageView;
}
}
Problem : When the application is first launched, UI is not getting populated with imageviews. In Logcat I could see control is flowing through doBackground(), onProgressUpdate() and onPostExecute().
When I click 'Refresh' button or If i navigate to some other activity or app and return to Movie app UI (onResume()) it is working perfectly fine. Images are displayed.
Many thanks in advance!
You should change updateMovies(); from onStart() to onCreateView. As Gabe Sechan said, you're wrong about the lifecycle. Try to do some research on the Fragment lifecycle.
Just you need to call method updateMovies(); from onCreateView() after posterGridView = (GridView) rootView.findViewById(R.id.gridview_movie);
remove call from start();
I am creating an android browser. I have a Favorites Page created with a ListActivity which gets its elements from an array named "elements". This is the code for the Favorites Activity:
package com.example.browser3;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Favorite extends ListActivity {
String[] elements={};
ArrayAdapter<String> adapter;
HomePage object=new HomePage();
public void setElements(int position,String element) {
elements[position]=element;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
elements = getIntent().getStringArrayExtra("name");
setListAdapter(new ArrayAdapter<String>(Favorite.this , android.R.layout.simple_list_item_1 , elements));
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
try{
Class ourClass = Class.forName("com.example.browser3.HomePage");// ce e aici aia porneste la click
Intent ourIntent = new Intent(Favorite.this , ourClass);
String s=elements[position];
ourIntent.putExtra("name", s);
startActivity(ourIntent);
}
catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
The array I am trying to send is from the Settings Activity, getting the data from an EditText, and when clicking the add button, to send the data in the new activity , but to also write it in the file to remain there after you reopen the browser.
So, my question is, why doesn't this work? Can someone help me? But please, be explicit. I watched several tutorials and it seems fine.
Code for Settings Activity:
package com.example.browser3;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Settings2 extends Activity{
EditText etAdress;
Button bAdd;
Button bRemove;
Button bMenu;
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.settings2);
super.onCreate(savedInstanceState);
bMenu=(Button)findViewById(R.id.bMenu);
bMenu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
clickHome();
}
});
etAdress=(EditText) findViewById(R.id.etAdress);
bAdd=(Button) findViewById(R.id.bAdd);
bAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
writeFile("lala.txt",etAdress);
String[] s={};
readFile("lala.txt",s);
Class ourClass = Class.forName("com.example.browser3.Favorite");
Intent ourIntent = new Intent(Settings2.this , ourClass);
ourIntent.putExtra("name", s);
startActivity(ourIntent);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
bRemove=(Button) findViewById(R.id.bRemove);
bRemove.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
}
private void clickHome(){
startActivity(new Intent("com.example.browser3.MENU"));
}
public void readFile(String fileName,String[] w){
try {
InputStream in=openFileInput(fileName);
if(in!=null){
InputStreamReader reader= new InputStreamReader(in);
BufferedReader buffreader= new BufferedReader(reader);
StringBuilder builder= new StringBuilder();
String str;
while((str=buffreader.readLine())!=null){
builder.append(str+ "\n");
String whole= builder.toString();
String[] split=whole.split("\\r?\\n");
for (int i = 0; i < split.length; i++) {
w = split;
}
}
in.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writeFile(String fileName, EditText x) {
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(fileName, MODE_APPEND));
out.write(x.getText().toString() + "\n");
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I hope this example will help you :
Passing ArrayList from one activity to another activity
Passing Object from one activity to another activity
Create Custom Class for that as follows :
public class SerIntArrData implements Parcelable{
public int[] intArr;
public int[] getIntArr() {
return intArr;
}
public void setIntArr(int[] intArr) {
this.intArr = intArr;
}
public SerIntArrData(int size) {
intArr = new int[size];
}
public SerIntArrData(Parcel in) {
intArr = (int[]) in.readSerializable();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeSerializable(intArr);
}
public static final Parcelable.Creator<SerIntArrData> CREATOR = new Parcelable.Creator<SerIntArrData>() {
#Override
public SerIntArrData createFromParcel(Parcel in) {
return new SerIntArrData(in);
}
#Override
public SerIntArrData[] newArray(int size) {
return new SerIntArrData[size];
}
};
}
Set Value in Parcelable
SerIntArrData mParcelable = new SerIntArrData();
mParcelable.setIntArr(intArrvalue);
Intent i = new Intent(this, TargetActivity.class);
i.putExtra("parcel",mParcelable);
startActivity(i);
Read the data in the target activity
SerIntArrData myParcelable = extras.getParcelable("parcel");
intArrValue = myParcelable.getIntArr();
I have written a code to get all the videos related to a specific user in YouTube as follows:
import java.util.ArrayList;
import java.util.Collection;
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 org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.example.tstnetconnwithjson.tables.custome;
import com.example.tstnetconnwithjson.tables.videos;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
Button search; ;
TextView name ;
ListView listview ;
ArrayList<videos > videolist;
ArrayAdapter< videos > adapter ;
AlertDialog.Builder alert ;
ProgressDialog progressdialog ;
EditText name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videolist = new ArrayList<videos>();
adapter = new ArrayAdapter<videos>(this, android.R.layout.simple_list_item_1 , android.R.id.text1,videolist);
name=(EditText) findViewById(R.id.editText1);
alert = new Builder(this);
alert.setTitle("Warnning" ) ;
alert.setMessage("You want to connect to the internet ..? " );
alert.setNegativeButton("No ", null);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
String username=name.getText().toString();
new connection().execute("https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc");
}
});
progressdialog = new ProgressDialog(this);
progressdialog.setMessage("Wait Loading .... ");
progressdialog.setCancelable(false);
search = (Button) findViewById(R.id.button1);
name = (TextView) findViewById(R.id.textView1);
listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
search.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
alert.show();
}
});
}
class connection extends AsyncTask<String, Integer, String>{
#Override
protected void onPreExecute() {
progressdialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
String s = GetUrlBody(arg0[0]);
return s;
}
#Override
protected void onPostExecute(String result) {
try{
JSONObject jo =(JSONObject) new JSONTokener(result).nextValue();
JSONObject feed = jo.optJSONObject("data");
JSONArray entry = feed.optJSONArray("items");
for(int i = 0 ; i<entry.length() ; i++){
String title = entry.getJSONObject(i).getString("title");
String thumbURL = entry.getJSONObject(i).getJSONObject("thumbnail").getString("sqDefault");
Log.d("after get image", "ok")
String url;
try {
url = entry.getJSONObject(i).getJSONObject("player").getString("mobile");
} catch (JSONException ignore) {
url = entry.getJSONObject(i).getJSONObject("player").getString("default");
}
String description = entry.getJSONObject(i).getString("description");
Log.d("after get description", "ok");
videos videoobject=new videos();
videoobject.setDecscrption(description);
videoobject.setImageurl(thumbURL);
videoobject.setVediourl(url);
videoobject.setVideoname(title);
videolist.add(videoobject);
}
listview.setAdapter(new custome(MainActivity.this,videolist));
Log.d("AFTER set custome ", "before notify changes");
adapter.notifyDataSetChanged();
}catch(Exception exception) {
Log.d("exception ", "nock nock nock....");
Log.e("json ", exception.getMessage());
}
progressdialog.dismiss();
super.onPostExecute(result);
}
String GetUrlBody (String Url ){
HttpClient client = new DefaultHttpClient();
HttpGet gethttp = new HttpGet(Url);
try{
HttpResponse response = client.execute(gethttp);
if(response.getStatusLine().getStatusCode() == 200){
String save =
EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
return save;
}else {
return "Not Found";
}
}catch(Exception exception){}
return null;
}
}
}
Where the custome class is extends from base adapter in order to have list view with image view set to video image and text view set to video title.
In log cat messages the result are existed but my list view returns empty.
Can any one tell me why?
here is the code for costume list view:
public class custome extends BaseAdapter {
ArrayList<videos> data=new ArrayList<videos>();
android.content.Context context1;
android.widget.TextView name;
ImageView picture;
public custome(Context context,ArrayList<videos>arrayList) {
// TODO Auto-generated constructor stub
context=context;
arrayList=data;
}
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return data.get(arg0);
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
public View getView(int arg0, View arg1, ViewGroup arg2) {
View view=arg1;
if(view==null)
{
LayoutInflater layoutInflater=(LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=layoutInflater.inflate(R.layout.listvideo,null);
}
name=(TextView) view.findViewById(R.id.textView1);
picture=(ImageView) view.findViewById(R.id.imageView1);
videos video = data.get(arg0);
name.setText(video.getVideoname());
URL url = null;
try {
url = new URL(video.getImageurl());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
picture.setImageBitmap(bitmap);
return view;
}
}
The problem is in your assigning code of custome constructor:
Use this constructor:
public custome(Context context,ArrayList<videos> arrayList) {
context=context;
//arrayList=data;<<< WRONG
data=arrayList;//<<<<<<< Correct way of assigning
}
You are overriding your adapter here:
listview.setAdapter(new custome(MainActivity.this,videolist));
Remove this line
I am new to android so please be patient with me , I am creating this code to draw a gridview of images , and I am using asynctask , however my problem is the asynctask is running so binding the image becomes late and the image isnt shown , when i debug it's shown because i delay it so i know the problem but i hope someone fixes the syntax for me , thanks alot .
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
public class ImagesAdapter extends BaseAdapter implements ListAdapter {
private Context mContext;
ImageView currentImageView;
Bitmap bmImg;
// Constructor
public ImagesAdapter(Context c) {
super();
mContext = c;
GridViewConfig.addImageUrls();
}
#Override
public int getCount() {
return GridViewConfig.getResim_list().size();
}
#Override
public Object getItem(int position) {
return GridViewConfig.getResim_list().get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null)
{
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(100, 100));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 5, 5, 5);
} else {
imageView = (ImageView) convertView;
}
downloadFile(GridViewConfig.getResim_list().get(position));
imageView.setImageBitmap(bmImg);
// imageView.setImageDrawable(LoadImageFromURL(GridViewConfig
// .getResim_list().get(position)));
return imageView;
}
void downloadFile(String fileUrl) {
AsyncTask<String, Object, String> task = new AsyncTask<String, Object, String>() {
#Override
protected String doInBackground(String... params) {
URL myFileUrl = null;
try {
myFileUrl = new URL(params[0]);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String unused) {
/* if (currentImageView == null) {
currentImageView = new ImageView(mContext);
}
currentImageView.setImageBitmap(bmImg); */
}
};
task.execute(fileUrl);
}
gridviewconfig class returns the needed images.
Take a look at http://developer.android.com/training/displaying-bitmaps/index.html There is a BitmapFun sample project/app with the grid and many useful stuff. I recommend you not to reinvent the wheel but to use google's code who are the creators of Android
also I suggest you to study some LazyList implementation