I am trying to pass 2 String[] from doinbackground to fragment where i have RecyclerView. I also tried setter getter method but still no luck
Here is my Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.activity_friend_list,container,false);
recyclerView= (RecyclerView) view.findViewById(R.id.RecyclerViewForFriendList);
//WANTS TO REPLACE THESE TWO ARRAY WITH WHICH I AM GETTING IN DOINBACKGROUND
Name=getResources().getStringArray(R.array.left_Drawer_Menu);
Image=getResources().obtainTypedArray(R.array.user_image);
recyclerView.setHasFixedSize(true);
adapter=new RecyclerFriendListAdapter(getActivity(),Distance,Image,LastSeen,Name);
recyclerView.setAdapter(adapter);
layoutManager=new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
return view;
}
Here is my AsyncTask Class
protected String[] doInBackground(String... params) {
try {
URL url=new URL(URL_Path);
connection= (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer stringBuffer=new StringBuffer();
while ((line=reader.readLine())!=null){
stringBuffer.append(line);
}
String completeJSON=stringBuffer.toString();
JSONArray parentArray=new JSONArray(completeJSON);
String[] Name=new String[parentArray.length()];
String[] ImagePath=new String[parentArray.length()];
for (int i = 0; i <parentArray.length() ; i++) {
JSONObject childObject=parentArray.getJSONObject(i);
String Fname=childObject.getString("First_Name") ;
String Lname=childObject.getString("Last_Name") ;
Name[i]=Fname+" "+Lname;
ImagePath[i]=childObject.getString("Image");
Log.d(TAG,"String Arrays "+Name[i]+" "+ ImagePath[i]);
//GETTING ALL VALUES IN LOG SUCCESSFULLY
}
return Name;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
try {
connection.disconnect();
if (reader!=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String[] strings) {
super.onPostExecute(strings);
}
I am calling AsyncTask Execute Method in Toolbar of Parent Activity Of Fragment
UPDATE:
1) As #BryanDunlap Asked for onPostExecute (its just implemented,No code inside it) And How to return both arrays to get in Fragment
2) #IrisLouis suggested to implement interface that's how i did with setter and getter but i wasn't work
ublic class WrapperClass {
private String[] Name;
private String[] ImagePath;
public String[] getImagePath() {
return ImagePath;
}
public void setImagePath(String[] imagePath) {
ImagePath = imagePath;
}
public String[] getName() {
return Name;
}
public void setName(String[] name) {
Name = name;
}
How i set this in AsyncTask
Name[i]=Fname+" "+Lname;
ImagePath[i]=childObject.getString("Image");
Log.d(TAG,"String Arrays "+Name[i]+" "+ ImagePath[i]);
//LOG RETURNS VALUE OF BOTH ARRAYS
WrapperClass w=new WrapperClass();
w.setImagePath(ImagePath);
w.setImagePath(Name);
Getting in Fragment in onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
....
....
....
WrapperClass wrapperClass=new WrapperClass();
String[] Name=wrapperClass.getName();
String[] ImagePath=wrapperClass.getImagePath();
Log.d(TAG,Name.toString()+" "+ ImagePath.toString())
//IT RETURNS NULLS
Solution for you, can test it.
In class Asynctask make a interface callback results :
public class PageLoader extends AsyncTask<String, Void, String[] results> {
private Context context;
private LoaderListener mLoaderListener;
public PageLoader(Context context, LoaderListener mLoaderListener) {
this.context = context;
this.mLoaderListener = mLoaderListener;
}
public interface LoaderListener {
void onLoadCompleted(String[] results);
void onLoadFailed();
void onPreparing();
}
#Override
protected void onPreExecute() {
mLoaderListener.onPreparing();
}
#Override
protected String[] doInBackground(String... params) {
try {
URL url=new URL(URL_Path);
connection= (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer stringBuffer=new StringBuffer();
while ((line=reader.readLine())!=null){
stringBuffer.append(line);
}
String completeJSON=stringBuffer.toString();
JSONArray parentArray=new JSONArray(completeJSON);
String[] Name=new String[parentArray.length()];
String[] ImagePath=new String[parentArray.length()];
for (int i = 0; i <parentArray.length() ; i++) {
JSONObject childObject=parentArray.getJSONObject(i);
String Fname=childObject.getString("First_Name") ;
String Lname=childObject.getString("Last_Name") ;
Name[i]=Fname+" "+Lname;
ImagePath[i]=childObject.getString("Image");
Log.d(TAG,"String Arrays "+Name[i]+" "+ ImagePath[i]);
//GETTING ALL VALUES IN LOG SUCCESSFULLY
}
return Name;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
try {
connection.disconnect();
if (reader!=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String[] results) {
if (results!= null) {
mLoaderListener.onLoadCompleted(results);
} else {
mLoaderListener.onLoadFailed();
}
}
}
In Activity you execute Asynctask.
In Fragment you must implements LoaderListener and Override three function.
Ex : YourFragment extends Fragment implements LoaderListener
You can handle results callback in onLoadCompleted
Ex :
#Override
public void onLoadCompleted(String[] results){
//Do something with results
}
Related
my error log
I tried to load list view in my fragment.But my app crashes on clicking the button to populate my listview. I don't know what error i did.Any help will be appreciated.I have tried most of the stuffs regarding this..But nothing works well.(i have removed some codes to avoid clumsy look)
Here is my Fragment code :
public class Func extends Fragment {
ArrayList<Flowers> flowersList = new ArrayList<Flowers>();
String url ="http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData";
#Override
public android.view.View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab2, container, false);
FlowerAdapter adapter=new FlowerAdapter(getActivity().getApplicationContext(),R.layout.flower_list_xml,flowersList);
ListView listView=(ListView)rootView.findViewById(R.id.listView);
listView.setAdapter(adapter);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
Button b = (Button)getView().findViewById(R.id.button);
b.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
new BackTask().execute(url);
}
});
}
// My Async task starts here
public class BackTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String result = null;
BufferedReader reader = null;
try {
URL url = new URL(strings[0]);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
Log.d("testhtt2", "test");
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Log.d("test44", sb.toString());
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return result;
}
}
#Override
protected void onPostExecute(String s){
try {
JSONArray ar =new JSONArray(s);
for (int i = 0; i < ar.length(); i++){
JSONObject jsonObject=ar.getJSONObject(i);
Flowers flowers= new Flowers();
flowers.setName(jsonObject.getString("NAME"));
flowersList.add(flowers);
}
} catch (JSONException e) {
e.printStackTrace();
}
You return null in your doInBackground, which you then attempt to parse as a JSONArray in your OnPostExecute. Return a proper String from your doInBackground method, and see if that helps.
Do a null check before using getView() like
if(getView()!=null){
//Your code
}
Also it is better to initialize the button in oncreate view using the rootview intead of getview()
EDIT:
Your network call which your are doing has to be moved to doInBackground as it should be done in background thread and fetch the result.The fetched result should be added to the list in onPostExecute.Hope this helps you
public class SampleClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
BufferedReader reader = null;
String result=null;
try {
URL url = new URL(strings[0]);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
Log.d("testhtt2", "test");
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Log.d("test44", sb.toString());
result= sb.toString();
} catch (Exception e) {
e.printStackTrace();
result= null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
result= null;
}
}
return result;
}
}
#Override
protected void onPostExecute(String s){
try {
JSONArray ar =new JSONArray(s);
for (int i = 0; i < ar.length(); i++){
JSONObject jsonObject=ar.getJSONObject(i);
Flowers flowers= new Flowers();
flowers.setName(jsonObject.getString("NAME"));
flowersList.add(flowers);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
you can try with view insteadof getView() in onViewCreated() method.
public class ListView extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab2, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button b = (Button) view.findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new BackTask().execute("http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData");
}
});
}
private class BackTask extends AsyncTask<String, Void, String> {
String result;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
result = Utility.executeHttpGet(params[0]);
} catch (Exception e) {
Log.e("ListView", e.getMessage(), e);
}
return result;
}
#Override
protected void onPostExecute(String s) {
try {
JSONArray ar = new JSONArray(s);
for (int i = 0; i < ar.length(); i++) {
JSONObject jsonObject = ar.getJSONObject(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Try this code
public class Listview extends Fragment {
ArrayList<Flowers> flowersList = new ArrayList<Flowers>();
String url ="http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData";
ListView listview;
View rootView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (rootView!= null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
rootView = inflater.inflate(R.layout.tab2, container, false);
} catch (InflateException ignored) {
}
listView=(ListView)rootView.findViewById(R.id.listView);
Button b = (Button)rootView.findViewById(R.id.button);
b.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
new BackTask().execute(url);
}
});
return view;
}
private class BackTask extends AsyncTask<String,String,String>{
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
return null;
}
#Override
protected void onPostExecute(String s){
try {
JSONArray ar =new JSONArray(s);
for (int i = 0; i < ar.length(); i++){
JSONObject jsonObject=ar.getJSONObject(i);
Flowers flowers= new Flowers();
flowers.setName(jsonObject.getString("NAME"));
flowersList.add(flowers);
}
FlowerAdapter adapter=new FlowerAdapter(getActivity(),R.layout.flower_list_xml,flowersList);
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
Hi I am using AsyncTaskLoader in my app and I have implemented that in MovieTaskLoader class but when I am implementing Loader callbacks in my fragment I am getting type conversion error in onCreateLoader() method.
MovieTaskLoader class:
class MovieTaskLoader extends AsyncTaskLoader<ArrayList<Movies>> {
MovieTaskLoader(Context context) {
super(context);
}
#Override
protected void onStartLoading() {
forceLoad();
}
#Override
public ArrayList<Movies> loadInBackground() {
//Building URL
URL url = null;
String jsonData = null;
Uri uri = Uri.parse(Utility.BASE_URL).buildUpon()
.appendPath("popular")
.appendQueryParameter("api_key", BuildConfig.api_key)
.build();
try {
url = new URL(uri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
//Downloading json data
HttpURLConnection urlConnection;
try {
assert url != null;
urlConnection = (HttpURLConnection) url.openConnection();
if(urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
jsonData = readStream(urlConnection.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
}
return getMovieData(jsonData);
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuilder response = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
private ArrayList<Movies> getMovieData(String jsonData){
ArrayList<Movies> movies = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(jsonData);
JSONArray results = jsonObject.getJSONArray("results");
for(int i=0; i<20; i++){
Movies movie = new Movies();
JSONObject object = results.getJSONObject(i);
movie.setTitle(object.getString("title"));
movie.setSynopsis("overview");
movie.setVote_avg("vote_average");
movie.setDate("release_date");
movies.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
return movies;
}
}
Fragment class:
public class PopularFragment extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<Movies>> {
public PopularFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_popular, container, false);
RecyclerView popularView = (RecyclerView) view.findViewById(R.id.popular_view);
GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
popularView.setLayoutManager(layoutManager);
popularView.setAdapter(new RecyclerViewAdapter());
return view;
}
#Override
public Loader<ArrayList<Movies>> onCreateLoader(int id, Bundle args) {
return new MovieTaskLoader(getContext());
}
#Override
public void onLoadFinished(Loader<ArrayList<Movies>> loader, ArrayList<Movies> data) {
}
#Override
public void onLoaderReset(Loader<ArrayList<Movies>> loader) {
}
}
I am getting error in onCreateLoader() method and type conversion error is:
Required: "Loader"
Found: MovieTaskLoader
Check your imports. Make sure both are same versions like this
android.support.v4.content.AsyncTaskLoader<D>
android.support.v4.app.LoaderManager.LoaderCallbacks<D>
Im trying to get data from json. Actually it is working but i have a problem with listview.Im getting error.
Here is the code;
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView txt;
Places places=new Places();
ListView listView;
List<Places> PlacesList=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt= (TextView) findViewById(R.id.text);
listView= (ListView) findViewById(R.id.listView);
listView.setBackgroundColor(Color.BLACK);
new getData().execute("https://api.foursquare.com/v2/venues/search?ll=41,29&oauth_token=01ZV1VDLE41USSRAYJUXOWNJ2MXYCAVN1I2PQFLFBCD40XYI&v=20160304");
}
public class getData extends AsyncTask<String,String,List <Places>> {
HttpURLConnection conn=null;
URL url=null;
BufferedReader bReader=null;
String name=null;
#Override
protected List<Places> doInBackground(String... params) {
try {
//BURADA URL'E BAGLANDIK
url=new URL(params[0]);
conn= (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
//VERİ OKUMAK İÇİN STREAM KULLANACAZ
InputStream istream=conn.getInputStream();
bReader= new BufferedReader(new InputStreamReader(istream));
//VERİ DEPOLAMAK İÇİN StringBuffer
StringBuffer sBuffer=new StringBuffer();
String line="";
while((line=bReader.readLine())!=null){
sBuffer.append(line);
}
String JSONFinal=sBuffer.toString();
JSONObject jsonObject=new JSONObject(JSONFinal);
JSONArray jsonArray=jsonObject.getJSONObject("response").getJSONArray("venues");
StringBuffer finalBuffer=new StringBuffer();
for(int i=0;i<jsonArray.length();i++) {
JSONObject finalJsonObject = jsonArray.getJSONObject(i);
name = finalJsonObject.getString("name");
places.setName(name);
PlacesList.add(places);
}
return PlacesList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
finally {
conn.disconnect();
}
return null;
}
#Override
protected void onPostExecute( List<Places> PlacesList) {
super.onPostExecute(PlacesList);
ArrayAdapter adapter= new ArrayAdapter<Places>(getApplicationContext(),android.R.layout.simple_list_item_1,PlacesList);
listView.setAdapter(adapter);
}
}
Places.java
public class Places {
int id,lat,lng;
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
So what is the problem?
It displays like that because you have passed Places object to your list view, and you haven't provided which fields to show in your list view from Places object , you should probably provide toString() method in your Places object to see your list with name or you should create your own adapter implementation
To see your listview with names
add this in your Places class
public void toString(){
return name;
}
Looks to me like you haven't overridden the toString() method of your Places class.
Add this to your Places class:
#Override
public String toString(){
return name;
}
See if that helps.
The Adapter is calling the toString() method of Places Object superclass, which is returning a hash of the Places object.
That's what's being printed.
I have an Activity called Myprofile and a baseAdapter called Myprofile_CustomView on my activity I get Json data which then I convert into a ArrayList with a hashmap and my question is how can I retrieve the values of the hashmap in the baseadapter ?
This is my activity Myprofile
public class Myprofile extends Activity {
String URI_URL;
Integer page;
ProgressBar pb;
ListView mm;
Myprofile_CustomView BA;
ArrayList<HashMap<String,String>> userslist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myprofile);
URI_URL = getResources().getString(R.string.PathUrl) + "/api/myprofile";
page=0;
// Listview for adapter
mm= (ListView)findViewById(R.id.myprofiles);
new Myprofile_Async().execute();
}
public class Myprofile_Async extends AsyncTask<String,String,String> {
HttpURLConnection conn;
URL url;
String result="";
DataOutputStream wr;
int id;
#Override
protected void onPreExecute() {
super.onPreExecute();
pb=(ProgressBar)findViewById(R.id.progressBar);
pb.setVisibility(View.VISIBLE);
id= getIntent().getExtras().getInt("id");
// page Int is used to keep count of scroll events
if(page==0)
{page=1;}
else {page=page+1;}
Toast.makeText(Myprofile.this,""+page,Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... params) {
// Gets data from api
BufferedReader reader=null;
String cert="id="+id+"&page="+page;
try{
url = new URL(URI_URL);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(cert);
wr.flush();
wr.close();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sBuilder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sBuilder.append(line + "\n");
}
result = sBuilder.toString();
reader.close();
conn.disconnect();
return result;
}
catch (Exception e)
{
e.printStackTrace();
}
System.err.println("cassies" + result);
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
HashMap<String,String> map= new HashMap<>();
JSONObject jsonn= new JSONObject(result);
JSONArray jArray = jsonn.getJSONArray("myprofile");
JSONObject jobject=null;
JSONArray sss= new JSONArray();
for(int i=0; i < jArray.length(); i++) {
jobject= jArray.getJSONObject(i);
map.put("fullname",jobject.getString("fullname"));
sss.put(jobject);
}
jsonn.put("myprofile", sss);
// Add values to arrayList
userslist.add(map);
// Send information to BaseAdapter
BA= new Myprofile_CustomView(userslist,Myprofile.this);
mm.setAdapter(BA);
} catch (Exception e) {
System.err.println("mpee: " + e.toString());
}
pb.setVisibility(View.INVISIBLE);
}
}
}
this part above I have no issues with my problem is in the BaseAdapter with the ArrayList userList I don't know how to get HashMap keys from it. I am naming the keys because I have other fields that I will eventually do
public class Myprofile_CustomView extends BaseAdapter {
JSONObject names;
Context ctx;
LayoutInflater myiflater;
ArrayList<HashMap<String,String>> usersList;
// Have data come in and do a toast to see changes
public Myprofile_CustomView(ArrayList<HashMap<String,String>> arr, Context c) {
notifyDataSetChanged();
ctx = c;
usersList= arr;
myiflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
try {
JSONArray jaLocalstreams = names.getJSONArray("myprofile");
return jaLocalstreams.length();
} catch (Exception e) {
Toast.makeText(ctx, "Error: Please try again", Toast.LENGTH_LONG).show();
return names.length();
}
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
MyViewHolder holder=null;
try {
if(row==null) {
LayoutInflater li = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = li.inflate(R.layout.zmyprofile,parent,false);
holder=new MyViewHolder(row);
row.setTag(holder);
}
else
{
holder=(MyViewHolder)row.getTag();
}
// How can I get HashMap value for fullname here so I can set it to to Text
String fullname= usersList
holder.fullname.setText(fullname);
return row;
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
class MyViewHolder{
TextView fullname;
MyViewHolder(View v)
{
fullname= (TextView)v.findViewById(R.id.fullname);
}
}
}
getCount should return the size of your dataset. In your case usersList
public int getCount() {
return usersList == null ? 0 : userLists.size();
}
int getView you want to retrieve the item at position:
HashMap<String, String> item = usersList.get(i);
String fullname = item.get("fullname");
the value of position changes with the scrolling,
I coded a class which starts a http connection for getting the text of e.g. website.
I used AsyncTask but I got NetworkOnMainException. May u help me?
The class
public class getXMLData extends AsyncTask<String, Void, String> {
TextView _textview;
public getXMLData(TextView textview) {
_textview = textview;
}
protected String doInBackground(String... url)
{
String _text = "";
try {
try {
URL _url = new URL(url[0]);
HttpURLConnection con = (HttpURLConnection) _url.openConnection();
_text = readStream(con.getInputStream());
}
catch (Exception e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
return _text;
}
protected void onPostExecute(String result)
{
_textview.setText(result.toCharArray(), 0, result.length());
}
private String readStream(java.io.InputStream in) {
java.io.BufferedReader reader = null;
String result = "";
reader = new BufferedReader(new InputStreamReader(in));
try {
while ((reader.readLine() != null)) {
result = result + reader.readLine();
}
}
catch (java.io.IOException i)
{
}
finally
{
try {
reader.close();
}
catch (java.io.IOException e) {
e.printStackTrace();
}
}
return result;
}
Here how I start the AsyncTask:
bu_aktualize.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_getXMLData.doInBackground("http://www.google.de");
}
});
Thanks for your help.
You do not call doInBackground() yourself. Instead, you call execute() or executeOnExecutor() to start the AsyncTask.
You may wish to review the documentation for AsyncTask, which shows an example of setting up an AsyncTask, including a call to execute().