I have a Baseadapter for a listview, when 1 of the elements inside gets clicked it is supposed to execute an AsyncTask. The onClick is inside Baseadapter and that works however the async execute is not working here is my baseAdapter
public class LocalFeed_CustomView extends BaseAdapter {
JSONObject names;
Context ctx;
LayoutInflater myiflater;
public LocalFeed_CustomView(){}
public LocalFeed_CustomView(JSONObject arr,Context c) {
ctx = c;
names = arr;
// myiflater = (LayoutInflater)c.getSystemService(c.LAYOUT_INFLATER_SERVICE);
// System.err.println("vv:" + arr);
}
#Override
public int getCount() {
try {
JSONArray jaLocalstreams = names.getJSONArray("localstreams");
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) {
try {
if(convertView==null) {
LayoutInflater li = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.customadapter, null);
}
TextView votes= (TextView)convertView.findViewById(R.id.votes);
JSONArray jaLocalstreams = names.getJSONArray("localstreams");
final JSONObject jsonObject = jaLocalstreams.getJSONObject(position);
jsonObject.getInt("id");
// the click works because the toast message fires
votes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
int Stream_ID= jsonObject.getInt("id");
SharedPreferences myaccount = ctx.getSharedPreferences("userInfo", ctx.MODE_PRIVATE);
int Profile_id=myaccount.getInt("id", 0);
Toast.makeText(ctx, "click worked", Toast.LENGTH_SHORT).show();
// the execute below is not firing off
new Add_Votes(Stream_ID,Profile_id).execute();
}
catch (Exception e)
{
e.getCause();
}
}
});
return convertView;
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
}
As you can see the execute is not working and both of the int values have numbers in them. This is my AsyncTask
public class Add_Votes extends AsyncTask<String,String,String> {
HttpURLConnection conn;
URL url;
String result="";
DataOutputStream wr;
String Stream_URL;
Activity m;
int stream_id,profile_id;
public Add_Votes(int stream_id,int profile_id)
{
this.stream_id=stream_id;
this.profile_id=profile_id;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Stream_URL= m.getResources().getString(R.string.PathUrl)+"/api/addvote";
//this Toast never fires off
Toast.makeText(m.getApplicationContext(),"clicked",Toast.LENGTH_SHORT);
}
#Override
protected String doInBackground(String... params) {
BufferedReader reader=null;
try{
url = new URL(Stream_URL);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
String cert="id="+profile_id+"&stream_id="+stream_id;
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();
}
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
Toast.makeText(m.getApplicationContext(),"Voted",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(m.getApplicationContext(),"Inconclusive",Toast.LENGTH_SHORT).show();
}
}
}
Add_Votes is only an AsyncTask there is no activity associated with it. Any suggestions on how I can call an AsyncTask from a baseadapter would be great. It needs to be from a baseadapter because each row has different values depending on the item clicked which then I pass on to the Async Task.
One thing I notice is you are using a variable Activity m and you have not initialised it in your AsyncTask. try passing a context from your BaseAdapter to AsyncTask.
In Add_Votes :
private Context context;
public Add_Votes(Context context ,int stream_id,int profile_id)
{
this.stream_id=stream_id;
this.profile_id=profile_id;
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(context,"clicked",Toast.LENGTH_SHORT).show();
}
In your BaseAdapter:
Add_Votes add_Votes = new Add_Votes(ctx,Stream_ID,Profile_id);
add_Votes.execute();
Related
I want to get Google spreadsheet data to my Android app.
I have looked for some example.
https://www.telerik.com/blogs/google-spreadsheet-as-data-source-android
This is a sample that I found.
It can run, but when I change his spreadsheet to my spreadsheet.
It will fail.
I do not know what's wrong.
This is my sheet:
https://docs.google.com/spreadsheets/d/1pIj08MUjTNZscHbKkbJJ2eNR1RYlhJLW7qDrcWRnJMM/edit?usp=sharing
This is my Code:
AsyncResult.java
interface AsyncResult
{ void onResult(JSONObject object);
}
DownloadWebpageTask.java
public class DownloadWebpageTask extends AsyncTask<String, Void, String> {
AsyncResult callback;
public DownloadWebpageTask(AsyncResult callback) {
this.callback = callback;
}
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to download the requested page.";
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
// remove the unnecessary parts from the response and construct a JSON
int start = result.indexOf("{", result.indexOf("{") + 1);
int end = result.lastIndexOf("}");
String jsonResponse = result.substring(start, end);
try {
JSONObject table = new JSONObject(jsonResponse);
callback.onResult(table);
} catch (JSONException e) {
e.printStackTrace();
}
}
private String downloadUrl(String urlString) throws IOException {
InputStream is = null;
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int responseCode = conn.getResponseCode();
is = conn.getInputStream();
String contentAsString = convertStreamToString(is);
return contentAsString;
} finally {
if (is != null)
is.close();
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {}
return sb.toString();
}
}
Team.java
public class Team {
private String position;
public Team(String position)
{
this.setPosition(position);
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
}
TeamsAdapter.java
public class TeamsAdapter extends ArrayAdapter<Team> {
Context context;
private ArrayList<Team> teams;
public TeamsAdapter(Context context, int textViewResourceId, ArrayList<Team>
items) {
super(context, textViewResourceId, items);
this.context = context;
this.teams = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.team, null);
}
Team o = teams.get(position);
if (o != null) {
TextView pos = (TextView) v.findViewById(R.id.position);
pos.setText(String.valueOf(o.getPosition()));
}
return v;
}
}
mainactivity.java
public class MainActivity extends AppCompatActivity {
private static final String DEBUG_TAG = "HttpExample";
ArrayList<Team> teams = new ArrayList<Team>();
ListView listview;
Button btnDownload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listview);
btnDownload = (Button) findViewById(R.id.btnDownload);
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
btnDownload.setEnabled(true);
} else {
btnDownload.setEnabled(false);
}
}
public void buttonClickHandler(View view) {
new DownloadWebpageTask(new AsyncResult() {
#Override
public void onResult(JSONObject object) {
processJson(object);
}
}).execute("https://spreadsheets.google.com/tq?
key=1pIj08MUjTNZscHbKkbJJ2eNR1RYlhJLW7qDrcWRnJMM");
}
private void processJson(JSONObject object) {
try {
JSONArray rows = object.getJSONArray("rows");
for (int r = 0; r < rows.length(); ++r) {
JSONObject row = rows.getJSONObject(r);
JSONArray columns = row.getJSONArray("c");
String position = columns.getJSONObject(0).getString("v");
Team team = new Team(position);
teams.add(team);
}
final TeamsAdapter adapter = new TeamsAdapter(this, R.layout.team,
teams);
listview.setAdapter(adapter);
} catch (JSONException e) {}
}
}
That's the link you should be using
https://spreadsheets.google.com/feeds/list/1pIj08MUjTNZscHbKkbJJ2eNR1RYlhJLW7qDrcWRnJMM/od6/public/values?alt=json
since I'm still kinda just starting out on more advanced android development I wanna learn more about APIs and how to fetch JSON data into a ListView.
Let's say I want to be able to search for an actor and in return get all the movies he's been involved with displaying in a listview. I've been glancing at retrofit, but not sure if it does the job I'm looking for.
I'll take any info regarding this matter. Links, snippets, you name it.
Step 1: create activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
>
<ListView
android:id="#+id/actorslist"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:color="#ffffff"
android:divider="#null"
android:scrollbars="none"
/>
</RelativeLayout>
Step 2: create your RequestSenderFiles
-first create one interface AsyncResponse.java
public interface AsyncResponse
{
void processFinish(Object output) throws JSONException;
}
-Now Create Another File RequestResponse.java
public class RequestResponse extends AsyncTask<String ,String,String>
{
Activity c;
public AsyncResponse delegate = null;
String req="";
HashMap<String,String> params;
boolean connect=true;
int responseCode;
String url;
ProgressDialog Loader;
public RequestResponse(AsyncResponse AsyncResponse, Activity context, String RequestMethod)
{
delegate = AsyncResponse;
c=context;
req=RequestMethod;
}
public RequestResponse(AsyncResponse AsyncResponse, Activity context, String RequestMethod, HashMap<String, String> postparam)
{
delegate = AsyncResponse;
c=context;
req=RequestMethod;
params=postparam;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
// your progressdialog your here
Loader=new ProgressDialog(c);
Loader.setMessage("Loading...");
Loader.show();
}
#Override
protected String doInBackground(String... params)
{
String json="";
Log.i("REposnse",""+params[0]);
url=params[0];
if(req.equals("GET"))
{
json=Client(params[0]);
}
else
{
json=ClientPost(params[0]);
}
Log.i("REposnse", "" + json);
return json;
}
#Override
protected void onPostExecute(String av)
{
super.onPostExecute(av);
if(connect)
{
try
{
delegate.processFinish(av);
}
catch (JSONException e)
{
e.printStackTrace();
}
try
{
if ((this.Loader != null) && this.Loader.isShowing())
{
this.Loader.dismiss();
}
}
catch (final IllegalArgumentException e)
{
// Handle or log or ignore
}
catch (final Exception e)
{
// Handle or log or ignore
}
finally
{
this.Loader = null;
}
}
else
{
try
{
if ((this.Loader != null) && this.Loader.isShowing())
{
this.Loader.dismiss();
}
}
catch (final IllegalArgumentException e)
{
// Handle or log or ignore
}
catch (final Exception e)
{
// Handle or log or ignore
}
finally
{
this.Loader = null;
}
c.runOnUiThread(new Runnable()
{
public void run()
{
if(req.equals("GET"))
{
RequestResponse requestget= RequestResponse(delegate, c);
requestget.execute(url);
}
else
{
RequestResponse requestpost = new RequestResponse(delegate, c, req, params);
requestpost.execute(url);
}
}
});
}
}
public String ClientPost(String url)
{
URL url1;
String response = "";
try
{
url1 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setReadTimeout(1500000);
conn.setConnectTimeout(1500000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(params));
writer.flush();
writer.close();
os.close();
responseCode=conn.getResponseCode();
Log.i("REposnse",""+responseCode);
if(responseCode == HttpsURLConnection.HTTP_OK)
{
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null)
{
response+=line;
}
}
else
{
connect=false;
response="";
}
}
catch (Exception e)
{
connect=false;
}
return response;
}
public String Client(String url)
{
String result = "";
try
{
URL apiurl =null;
HttpURLConnection conn;
String line;
BufferedReader rd;
apiurl = new URL(url);
conn = (HttpURLConnection) apiurl.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(1500000);
conn.setConnectTimeout(1500000);
responseCode=conn.getResponseCode();
Log.i("REposnse",""+responseCode);
if(responseCode==HttpsURLConnection.HTTP_OK)
{
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null)
{
result += line;
}
rd.close();
}
else
{
connect=false;
}
}
catch (Exception e)
{
connect=false;
}
return result;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet())
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
Log.i("REposnse",""+params);
return result.toString();
}
}
Step 3: create Activity MainActivity.java
public class MainActivity extends Activity
{
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState)
{
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main.xml);
list = (ListView) findViewById(R.id.actorslist);
request();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void request()
{
// for POST Request
//suppose you need to send some data to server to fetch the response from server
HashMap<String,String> data=new HashMap<String,String>();
data.put("id","12");
try
{
RequestResponse crr = new RequestResponse(new AsyncResponse()
{
#Override
public void processFinish(Object output) throws JSONException
{
output.toString();//your response
// for example you got the response like this
String actors = "{"data":[{"actorname":"A"},{"actorname","B"}]}";
fetchandapplydata(actors);
}
}, this,"POST",data);
crr.execute(yourserversideurltofetchdata);
}
catch (Exception e)
{
e.printStacktrace();
}
// for GET Request
try
{
RequestResponse crr = new RequestResponse(new AsyncResponse()
{
#Override
public void processFinish(Object output) throws JSONException
{
output.toString();//your response
// for example you got the response like this
String actors = "{"data":[{"actorname":"A"},{"actorname","B"}]}";
fetchandapplydata(actors);
}
}, this,"GET");
crr.execute(yourserversideurltofetchdata);
}
catch (Exception e)
{
e.printStacktrace();
}
//Depend upon the request method use the code and comment the rest code.
}
public void fetchandapplydata(String data)
{
JSONObject object=new JSONObject(data);
JSONArray actors=object.getJSONArray("data");
ArrayList<HashMap<String,String>> actorsdata=new ArrayList<HashMap<String, String>>();
for(int i=0;i<actors.length();i++)
{
JSONObject actor=actors.getJSONObject(i);
HashMap<String,String> actorsnames=new HashMap<String,String>();
actorsnames.put("name",actor.getString("actorname"));
actorsdata.add(actorsnames);
}
ActorAdapter actoradapter = new ActorAdapter(this, actorsdata);
list.setAdapter(actoradapter);
}
}
Step 4: Create ActorAdapter.java
public class ActorAdapter extends BaseAdapter
{
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
private Activity activity;
public ActorAdapter(Activity a, ArrayList<HashMap<String, String>> d)
{
activity = a;
data=d;
inflater = (LayoutInflater)Ced_activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount()
{
return data.size();
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
try
{
View vi;
vi = inflater.inflate(R.layout.actor_item, null);
TextView name= (TextView) vi.findViewById(R.id.name);
HashMap<String, String> actor = new HashMap<String, String>();
actor = data.get(position);
name.setText(actor.get("name"));
return vi;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
Step 5 : create actor_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main">
<TextView
android:layout_width="wrap_parent"
android:layout_height="wrap_parent"
android:id="#+id/name" />
</RelativeLayout>
This is step by step process for your question , still if you have any doubt feel free to ask us.
I written json and created url with the help of git.but now i am not able to get the requested data as result is coming null.Please help me in that
public class TestActivity extends AppCompatActivity {
Button btnHit;
ListView moviList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
btnHit= (Button) findViewById(R.id.btn);
moviList=(ListView)findViewById(R.id.lvMovie);
/* btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute("https://gist.githubusercontent.com/PoonamWadekar/5c69afdcbe9c68240c546f73bcb40c69/raw/050254dd568a972442cdff0d984c396b9b340b7f/movie.json");
}
});*/
}
public class JSONTask extends AsyncTask<String,String,List<MovieModel>>{
#Override
protected List<MovieModel> doInBackground(String... params) {
HttpURLConnection httpURLConnection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson=buffer.toString();
JSONObject parentObj=new JSONObject(finalJson);
JSONArray parentArray=parentObj.getJSONArray("movies");
List<MovieModel> movieModelList=new ArrayList<>();
for (int i=0; i<parentArray.length() ; i++)
{
JSONObject finalObj=parentArray.getJSONObject(i);
MovieModel movieModel=new MovieModel();
movieModel.setMovie(finalObj.getString("movie"));
movieModel.setYear(finalObj.getInt("year"));
movieModel.setRating((float) finalObj.getDouble("rating")/2);
movieModel.setStory(finalObj.getString("story"));
//movieModel.setImage(finalObj.getString("image"));
List<MovieModel.Caste> casteList=new ArrayList<>();
for (int j=0;j<finalObj.getJSONArray("caste").length();j++){
MovieModel.Caste caste=new MovieModel.Caste();
caste.setName(finalObj.getJSONArray("caste").getJSONObject(j).getString("name"));
casteList.add(caste);
}
movieModel.setCasteList(casteList);
movieModelList.add(movieModel);
Log.d("hi","list+++++++++++++++++++++++" +movieModelList);
}
return movieModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null)
httpURLConnection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<MovieModel> result) {
super.onPostExecute(result);
if (result==null){
Log.d("Hi","sorry no result");
return;
}
//set data to recycler view
MovieAdapter adapter=new MovieAdapter(getApplicationContext(),R.layout.movie_cell,result);
moviList.setAdapter(adapter);
}
}
public class MovieAdapter extends ArrayAdapter{
private List<MovieModel> movieModelList=new ArrayList<MovieModel>();
private int resource;
LayoutInflater inflater;
public MovieAdapter(Context context, int resource, List<MovieModel> objects) {
super(context, resource, objects);
movieModelList=objects;
this.resource=resource;
inflater= (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView==null)
{
convertView=inflater.inflate(resource,null);
}
ImageView movieIcon;
TextView name;
TextView year;
RatingBar ratingBar;
TextView tvCaste;
TextView story;
movieIcon= (ImageView) convertView.findViewById(R.id.place_image);
name= (TextView) convertView.findViewById(R.id.tv_name);
year= (TextView) convertView.findViewById(R.id.tv_year);
ratingBar= (RatingBar) convertView.findViewById(R.id.rt_ratebar);
tvCaste= (TextView) convertView.findViewById(R.id.tv_cast);
story= (TextView) convertView.findViewById(R.id.tv_story);
name.setText(movieModelList.get(position).getMovie());
year.setText(" year -"+ movieModelList.get(position).getYear());
StringBuffer stringBuffer=new StringBuffer();
for (MovieModel.Caste caste: movieModelList.get(position).getCasteList()){
stringBuffer.append(caste.getName() + ",");
}
tvCaste.setText(stringBuffer);
story.setText(movieModelList.get(position).getStory());
// rating bar
ratingBar.setRating(movieModelList.get(position).getRating()/2);
return convertView;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actionbar_profile,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id==R.id.refresh){
String url="https://gist.githubusercontent.com/PoonamWadekar/5c69afdcbe9c68240c546f73bcb40c69/raw/9e3de75ffa48c70f81ad07b7623e5fd0789142f0/movie.json";
Log.d("url____",url);
new JSONTask().execute(url);
return true;
}
return super.onOptionsItemSelected(item);
}
}
It is working fine on my device.
Few doubts regarding your scenario.
Do you have internet permission set in manifest.xml file
Are you using emulator for running application?
If your are using WiFi, try reconnecting and check again.
Are you using VPN? If yes then disconnect from VPN and try again.
Thanks
I am have sql DB and I am trying to display queried values in a listView. I created a custom adapter for the listView. problem is
I am not able to see any data displayed on my listView.
code of main
public class _songs_playlist extends AppCompatActivity {
ArrayList<songsarray> listofsoongs = new ArrayList<songsarray>();
private static int SPLASH_TIME_OUT=2000;
AlertDialog alertDialog;
private boolean loggedIn = false;
String type;
String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity__songs_playlist);
new JSONParse().execute();
MyCustomAdapterSongs itemsAdapter = new MyCustomAdapterSongs(this, listofsoongs);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(itemsAdapter);
itemsAdapter.notifyDataSetChanged();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
alertDialog=new AlertDialog.Builder(_songs_playlist.this).create();
alertDialog.setTitle("Upadting Data");
pDialog = new ProgressDialog(_songs_playlist.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
HTTPHandler sh = new HTTPHandler();
String login_URL = "http://2f179dfb.ngrok.io/getsong.php";
try {
//Fetching the boolean value form sharedpreferences
URL url = new URL(login_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
Log.e("RESULT", result);
JSONObject jsonObject = new JSONObject(result);
JSONArray result1 = jsonObject.getJSONArray("result");
for (int i = 0; i < result1.length(); i++) {
JSONObject c = result1.getJSONObject(i);
String id = c.getString("songID");
String names = c.getString("songName");
String ss = c.getString("singerName");
listofsoongs.add(new songsarray(ss,id,names));
}
return jsonObject;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
if(true)
{
}
else
{
}
}
}
}
code of custom array adapter
public class MyCustomAdapterSongs extends ArrayAdapter<songsarray> {
Context context;
ArrayList<songsarray> items;
public MyCustomAdapterSongs(Activity context, ArrayList<songsarray> songsarrays) {
super(context, 0, songsarrays);
this.context=context;
this.items=songsarrays;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.itemlist, parent, false);
}
TextView nameTextView = (TextView) listItemView.findViewById(R.id.textView1);
nameTextView.setText(currentAndroidFlavor.getSingername());
Log.e("hhhh", nameTextView.getText().toString());
TextView numberTextView = (TextView) listItemView.findViewById(R.id.textView2);
numberTextView.setText(currentAndroidFlavor.getSongname());
Log.e("jjjj", numberTextView.getText().toString());
CheckBox ch=(CheckBox)listItemView.findViewById(R.id.checkBox1);
ch.setSelected(currentAndroidFlavor.isSelected());
return listItemView;
}
#Override
public int getCount() {
if(items == null)
return 0;
return items.size();
}
#Override
public songsarray getItem(int i) {
return items.get(i);
}
}
Call itemsAdapter.notifyDataSetChanged() within onPostExecute.
Your list is empty until the AsyncTask finishes there.
You'll have to make the adapter a member variable of the Activity class
As in your code I can see you are updating the list in doInBackground but you are not notifying the adapter for the changes.
In onPostExecute method you need to call itemsAdapter.notifyDataSetChanged() and make sure it you are not calling it inside doInBackground as in background thread you can't to UI related work.
Check the EDITS in this code snippet
`
public class _songs_playlist extends AppCompatActivity {
ArrayList<songsarray> listofsoongs = new ArrayList<songsarray>();
private static int SPLASH_TIME_OUT=2000;
AlertDialog alertDialog;
private boolean loggedIn = false;
String type;
String result;
//EDIT 1: Make these member variables
MyCustomAdapterSongs itemsAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity__songs_playlist);
//EDIT 2: get references your views before AsyncTask
listView = (ListView) findViewById(R.id.listView1);
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
alertDialog=new AlertDialog.Builder(_songs_playlist.this).create();
alertDialog.setTitle("Upadting Data");
pDialog = new ProgressDialog(_songs_playlist.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
HTTPHandler sh = new HTTPHandler();
String login_URL = "http://2f179dfb.ngrok.io/getsong.php";
try {
//Fetching the boolean value form sharedpreferences
URL url = new URL(login_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
Log.e("RESULT", result);
JSONObject jsonObject = new JSONObject(result);
JSONArray result1 = jsonObject.getJSONArray("result");
for (int i = 0; i < result1.length(); i++) {
JSONObject c = result1.getJSONObject(i);
String id = c.getString("songID");
String names = c.getString("songName");
String ss = c.getString("singerName");
listofsoongs.add(new songsarray(ss,id,names));
}
return jsonObject;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
//EDIT 3: set your adapter here as this method will be called on the UI Thread
itemsAdapter = new MyCustomAdapterSongs(this, listofsoongs);
listView.setAdapter(itemsAdapter);
}
}
}
}
`
I am trying to fetch data using AsyncTask & displaying into a ListView. It never calls getView(), I checked getCount() return always 0.
MainActivityFragment.java
public class MainActivityFragment extends Fragment {
private final String LOG_TAG = MainActivityFragment.class.getSimpleName();
SourceAdapter adapter;
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
adapter = new SourceAdapter(getActivity());
ListView listView = (ListView) rootView.findViewById(R.id.listView);
listView.setAdapter(adapter);
Log.d(LOG_TAG,"after list view set to adapter");
return rootView;
}
#Override
public void onStart() {
new FetchDataTask().execute();
super.onStart();
}
public class FetchDataTask extends AsyncTask<String, Void, SourceObject[]>{
private final String LOG_TAG = FetchDataTask.class.getSimpleName();
private SourceObject[] getSourceDataFromJson(String jsonStr)throws JSONException{
JSONArray jsonArray = new JSONArray(jsonStr);
SourceObject[] sourceObjects = new SourceObject[jsonArray.length()];
for (int i=0; i<jsonArray.length();i++){
sourceObjects[i] = new SourceObject(
jsonArray.getJSONObject(i).getJSONObject("commit").getJSONObject("author").getString("name"),
jsonArray.getJSONObject(i).getJSONObject("commit").getJSONObject("author").getString("name"),
jsonArray.getJSONObject(i).getJSONObject("commit").getString("message")
);
}
return sourceObjects;
}
#Override
protected SourceObject[] doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String jsonStr = null;
try {
String baseUrl = "https://api.github.com/repos/rails/rails/commits";
URL url = new URL(baseUrl);
Log.d(LOG_TAG,"URL IS "+url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null)
return null;
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null){
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
jsonStr = buffer.toString();
Log.d(LOG_TAG,"JSON STRING "+jsonStr);
}catch (IOException e){
Log.e(LOG_TAG, "ERROR"+e);
return null;
}finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getSourceDataFromJson(jsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(SourceObject[] strings) {
adapter.notifyDataSetChanged();
super.onPostExecute(strings);
}
}
}
SourceAdapter.java
public class SourceAdapter extends BaseAdapter {
private final String LOG_TAG = SourceAdapter.class.getSimpleName();
Context context;
ArrayList<SourceObject> objects = new ArrayList<SourceObject>();
public SourceAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
Log.d(LOG_TAG,"getCount called "+objects.size());
return objects.size();
}
#Override
public Object getItem(int position) {
Log.d(LOG_TAG,"getItem called");
return objects.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d(LOG_TAG,"get view method is called");
SourceObject sourceObject = (SourceObject) getItem(position);
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_source,parent,false);
}
TextView personName = (TextView) convertView.findViewById(R.id.person_name);
TextView commit = (TextView) convertView.findViewById(R.id.xxx);
TextView commitMessage = (TextView) convertView.findViewById(R.id.commit_message);
personName.setText(sourceObject.getPersonName());
commit.setText(sourceObject.getCommit());
commitMessage.setText(sourceObject.getCommitMessage());
return convertView;
}
}
Please help.
You are not setting data retrieved from AsyncTask to adapter.
Add this method to your adapter class:
public void setItems(SourceObject[] items) {
this.objects = new ArrayList<SourceObject>();
for(SourceObject item : items){
this.objects.add(item);
}
this.notifyDataSetChanged();
}
And change onPostExecute of AsyncTask to:
#Override
protected void onPostExecute(SourceObject[] strings) {
adapter.setItems(strings);
super.onPostExecute(strings);
}