I am having problem to call onListItemClick() function after execution of onPostExecute(Void result)
Below is my code snippet .
package com.myapp.checkoutnhangout;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.List;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class CheckoutNearestPlaces extends ListActivity {
private String[] placeName;
private String[] imageUrl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetPlaces(this,getListView()).execute();
}
class GetPlaces extends AsyncTask<Void, Void, Void> {
Context context;
private ListView listView;
private ProgressDialog progressDialog;
public GetPlaces(Context context , ListView listView) {
this.context = context;
this.listView = listView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setIndeterminate(true);
progressDialog.setTitle("Loading");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
findNearLocation();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progressDialog.dismiss();
setListAdapter(new ArrayAdapter<String>(context,android.R.layout.simple_list_item_1,placeName));
// this.listView.setAdapter(new ArrayAdapter<String>(context,android.R.layout.simple_list_item_1,placeName));
}
public void onListItemClick(ListView listView , View v , int position , long id){
System.out.println("position------------"+placeName[position]);
}
public void findNearLocation() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
PlacesService placesService = new PlacesService("AIzaSyC3y3fOMTqTkCjNNETQTCKustG7BRk_eVc");
List<Place> findPlaces = placesService.findPlaces(28.6752, 77.4362, "");
int findPlacesSize = findPlaces.size();
placeName = new String[findPlacesSize];
imageUrl = new String[findPlacesSize];
for(int index = 0 ; index < findPlacesSize ; index ++) {
Place placeDetail = findPlaces.get(index);
// System.out.println("name of place : "+placeDetail.getName());
placeName[index] = placeDetail.getName();
// System.out.println("url of place : "+placeDetail.getIcon());
imageUrl[index] = placeDetail.getIcon();
}
}
}
}
Above code use google palce api and display list of locations on the basis of user's interest .
After that , I want to call onListItemClick() function , so that I can call another activity on each item click.
Any help will be appreciable.
remove
public void onListItemClick(ListView listView , View v , int position , long id){
System.out.println("position------------"+placeName[position]);
}
from class GetPlaces
and put in CheckoutNearestPlaces
Related
Good afternoon,
I'm still a beginner in programming, currently learning Android.
I am making a screen that captures some information from a website and moves to a list view. The code below works when I use only the main page of the site, when I try to move to page 2 instead of adding to the end of the Array, it overwrites the entire Array.
I have reached the limit of my knowledge, I can kick it a silly mistake in how they are built, but I could not reach the solution alone.
I'm sorry if I have any typos, I'm using a translator.
package br.com.testejsoup.eu.testejsoup;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private ListView conteudo;
String[] aniNomes;
String[] aniLinks;
ArrayAdapter<String> adaptador;
Document doc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
conteudo = findViewById(R.id.html_conteudo);
new doit().execute();
conteudo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int posicao = position;
Intent intent = new Intent(MainActivity.this, Episodio.class);
intent.putExtra("aniLinks", aniLinks[posicao]);
//Toast.makeText(getApplicationContext(), aniLinks[posicao], Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
public class doit extends AsyncTask<Void, Void, Void>{
String URL = "http://www.URL.com/lancamentos?page=";
String nomeExp;
Elements nome;
Elements links;
int paginas = 5;
#Override
protected Void doInBackground(Void... voids) {
try {
for (int i=1; i<= paginas;i++) {
String new_URL = URL + i;
doc = Jsoup.connect(new_URL).get();
nome = doc.select("div.nome-thumb a.tt");
links = doc.select("div.nome-thumb a.tt");
aniNomes = new String[nome.size()];
aniLinks = new String[links.size()];
for(Element nomeTemp : nome){
nomeExp = nomeTemp.text();
adaptador.add(nomeExp);
}
}
for (int i = 0; i < nome.size(); i++) {
aniNomes[i] = nome.get(i).text();
}
for (int i = 0; i < links.size(); i++) {
aniLinks[i] = links.get(i).attr("abs:HREF");
}
adaptador = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, aniNomes);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
conteudo.setAdapter(adaptador);
}
}
}
New code after the proposed modification.
THANKS FOR THE HELP!!!
package br.com.testejsoup.eu.testejsoup;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ListView conteudo;
ArrayList<String> aniNomes = new ArrayList<>();
ArrayList<String> aniLinks = new ArrayList<>();
ArrayAdapter<String> adaptador;
Document doc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
conteudo = findViewById(R.id.html_conteudo);
new doit().execute();
conteudo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int posicao = position;
Intent intent = new Intent(MainActivity.this, Episodio.class);
intent.putExtra("aniLinks", aniLinks.get(position));
//Toast.makeText(getApplicationContext(), aniLinks[posicao], Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
public class doit extends AsyncTask<Void, Void, Void>{
String URL = "http://www.URL.com/lancamentos?page=";
String nomeExp;
Elements nome;
Elements links;
int paginas = 5;
#Override
protected Void doInBackground(Void... voids) {
try {
for (int i=1; i<= paginas;i++) {
String new_URL = URL + i;
doc = Jsoup.connect(new_URL).get();
nome = doc.select("div.nome-thumb a.tt");
links = doc.select("div.nome-thumb a.tt");
for (Element nomeT : nome){
aniNomes.add(nomeT.text());
}
for (Element linkT : links){
aniLinks.add(linkT.attr("abs:HREF"));
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adaptador = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, aniNomes);
conteudo.setAdapter(adaptador);
}
}
}
Its because you're creating a new adapter in your asynctask and then in your onPostExecute method you're calling setAdapter which swaps out the old adapter and its entries with the new adapter and its new entries.
Rather than creating a new adapter in your asynctask I would just create an array/arraylist, add the new entries to it and then in your onPostExecute just append the entries from this array/list into the one and only adapter entry set.
I want to show a toast message but getContext() in Toast.makeText((getContext()," Message" , Toat.LENGTH_LONG.show())) is giving error
Cannot resolve Method.
The problem is that in which class I want to show the Toast message is not MainActivity class. This is AsyncTask class. Can i show Toast message in other classes (other than MainActivity class) as the above mentioned problem?
import android.os.AsyncTask;
import android.widget.Toast;
public class myClass extends AsyncTask<String, String, String> {
public myClass(double a, double b,Context context ) {
this.a = a;
this.b=b;
this.context = context;
}
protected String doInBackground(String... params) {
return null;
}
protected void onPostExecute(String result) {
Toast.makeText((getApplicationContext(), "Message", Toast.LENGTH_LONG).show();
}
}
Edit
I made the constructor (See above code) but in the MainActivity class I am calling in this way myClassObj = new myClass(a, b,this); but is giving error
myClas() in myClass cannot be applied to:
Expected Actual
Parameters Arguments
a: double a
b: double b
context: android.content.Context this(anonymous...view.View.OnClickListener)
Edit3
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
myClass Object;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
double age = 16;
double number = 33;
Object = new myClass(age,number,this);
}
});
}
}
SecondClass.
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
public class myClass extends AsyncTask<String, String, String> {
Context context;
double a;
double b;
public myClass(double a, double b,Context context ) {
this.a = a;
this.b=b;
this.context = context;
}
protected String doInBackground(String... params) {
return null;
}
protected void onPostExecute(String result) {
Toast.makeText((context), "Message", Toast.LENGTH_LONG).show();
}
}
When you are using this it refers to the enclosing class. In your case this is View.OnClickListener. But you need to pass the context of your Activity.
So you need to call it this way,
Object = new myClass(age,number, MainActivity.this);
You can use the ApplicationClass.getinstance().getApplicationContext();
Edit 3
Do this in your MainActivity:
Object = new myClass(age,number,MainActivity.this);
And do this in your myClass
Toast.makeText(context, "Message", Toast.LENGTH_LONG).show();
Edit 2
class MyClass extends AsyncTask<Void, Void, Void> {
int SPLASH_SHOW_TIME=3000;
Context context;
public MyClass(Context context ) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
Thread.sleep(SPLASH_SHOW_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Toast.makeText(context, "Created a server socket",Toast.LENGTH_LONG).show();
}
}
I am creating an eWallet application like many existing ones. I have lots of classes that do different stuff but i need some advice in a group of them. I have created a listview witch fetches the categories i have created and saved in a phpMyAdmin database. I am displaying this data on a list view successfully. This list view just shows the list of the categories to the user and if he clicks a list item a new activity appers which llows him to edit or delete the list item.
Now i used the same code (i lterally used the same code!) to create a second listview inside a dialog box. Imagine that this listview appears inside the dialog box when i click an edit text which has an on click listener. I successfully display the data in this second list view as well. Now on this dialog box when i click a list item/category (lets say Sports category) i want the name of the edit text to change to the category i chose. But i am confused because i use the same code and methods that open the edit and delete activity on my first list view. I hope i did not confuse you too much.
Here is the code that downloads the data in my list views.
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class ExDownloaderActivity extends AsyncTask<Void, Integer, String>
{
Context context;
String address;
ListView expenseListView;
ProgressDialog progressDialog;
public ExDownloaderActivity(Context context, String address, ListView exCategoryListView)
{
this.context = context;
this.address = address;
this.expenseListView = exCategoryListView;
}
//B4 JOB STARTS
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Fetch Data");
progressDialog.setMessage("Fetching Data...Please wait");
progressDialog.show();
}
#Override
protected String doInBackground(Void... params)
{
String data = downloadData();
return data;
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String string)
{
super.onPostExecute(string);
progressDialog.dismiss();
if(string != null)
{
ExParserActivity parser = new ExParserActivity(context, string, expenseListView);
parser.execute();
}
else
{
Toast.makeText(context, "Unable to download data",Toast.LENGTH_LONG).show();
}
}
private String downloadData()
{
//connect and get a stream of data
InputStream inputStream = null;
//to store each line
String line = null;
try
{
URL url = new URL(address);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
if(bufferedReader!= null)
{
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line + "\n");
}
}
else
{
return null;
}
return stringBuffer.toString();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if(inputStream != null)
{
try
{
inputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return null;
}
}
Second Class
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class ExParserActivity extends AsyncTask<Void, Integer, Integer>
{
Context context;
ListView exListView;
String data;
ArrayList<String> exCategories = new ArrayList<>();
ProgressDialog progressDialog;
public ExParserActivity(Context context, String data, ListView lv)
{
this.context = context;
this.data = data;
this.exListView = lv;
}
//B4 JOB STARTS
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Parser");
progressDialog.setMessage("Parsing...Please wait");
progressDialog.show();
}
//Heavy job
#Override
protected Integer doInBackground(Void... params)
{
return this.parse();
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Integer integer)
{
super.onPostExecute(integer);
progressDialog.dismiss();
if(integer == 1)
{
//ADAPTER
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, exCategories);
//ADAPT TO LIST VIEW
exListView.setAdapter(arrayAdapter);
//ON CLICK LISTENER
exListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
context.startActivity(new Intent(context, UpdateDeleteExCategories.class));
//Snackbar.make(view, exCategories.get(position), Snackbar.LENGTH_SHORT).show();
}
});
}
else
{
Toast.makeText(context, "Unable to Parse", Toast.LENGTH_LONG).show();
}
}
//PARSE RECEIVED DATA
private int parse()
{
try
{
//ADD THAT DATA TO JSON ARRAY FIRST
JSONArray jsonArray = new JSONArray(data);
//CREATE JO OBJECT TO HOLD A SINGLE ITEM
JSONObject jsonObject = null;
exCategories.clear();
//LOOP THROUGH THE ARRAY
for(int i = 0; i < jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
//RETRIEVE NAME
String exCatName = jsonObject.getString("exCatName");
//ADD IT TO ARRAY LIST
exCategories.add(exCatName);
}
//IF ITS SUCCESSFUL RETURN 1
return 1;
}
catch (JSONException e)
{
e.printStackTrace();
}
//IF IT IS NOT SUCCESSFUL RETURN 0
return 0;
}
}
Third Class
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.Calendar;
public class AddExpenseActivity extends SwipeFunctionActivity
{
private ImageView backImageView;
private TextView setDateTextView;
private EditText categoryEditText, amountEditText;
int year, month, day;
static final int DIALOG_ID = 0; //Initialise the variable to 0.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_expense);
final Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
setDateTextView = (TextView)findViewById(R.id.setDateTextView);
backImageView = (ImageView)findViewById(R.id.backImageView);
categoryEditText = (EditText)findViewById(R.id.categoryEditText);
amountEditText = (EditText)findViewById(R.id.amountEditText);
setDateTextView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
showDialog(DIALOG_ID);
}
});
categoryEditText.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
pickCategoryMethod();
}
});
backImageView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
backMethod();
}
});
}
#Override
protected Dialog onCreateDialog(int id)
{
if (id == DIALOG_ID)
{
return new DatePickerDialog(this, dpickerListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener dpickerListener = new DatePickerDialog.OnDateSetListener()
{
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
AddExpenseActivity.this.year = year;
month = monthOfYear + 1;
day = dayOfMonth;
showDate(AddExpenseActivity.this.year, month, day);
//Toast.makeText(AddExpenseActivity.this, "Selected date: " + dayOfMonth + " / " + (monthOfYear+1) + " / " + year, Toast.LENGTH_LONG).show();
}
};
private void showDate(int year, int month, int day)
{
setDateTextView.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
public void pickCategoryMethod()
{
String url = "http://192.168.0.3/myapp/fexcateg.php";
//
final Dialog dialog = new Dialog(AddExpenseActivity.this);
dialog.setContentView(R.layout.activity_pick_category);
dialog.setTitle(" Pick your Category");
final ListView pickCategoryListView = (ListView)dialog.findViewById(R.id.pickCategoryListView);
final ExDownloaderActivity downloader = new ExDownloaderActivity(this, url, pickCategoryListView);
//Execute download
downloader.execute();
//pickCategoryListView = (ListView)dialog.findViewById(R.id.pickCategoryListView);
//This makes the dialog visible.
dialog.show();
}
public void backMethod()
{
//startActivity(new Intent(getApplicationContext(), BalanceActivity.class));
finish();
}
#Override
public void onSwipeLeft()
{
super.onSwipeLeft();
startActivity(new Intent(getApplicationContext(), AddIncomeActivity.class));
finish();
}
#Override
public void onSwipeRight()
{
super.onSwipeRight();
startActivity(new Intent(getApplicationContext(), AddSavingActivity.class));
finish();
}
}
So for my problem now. I want when i click a category inside the dialog box, the categoryEditText variable i have in the trird class to change in the name of the item i clicked in the listview. First of all where do i have to write this code and secondly how to do it. I am kind of lost becasue is really a big app:/
Many thanks !!!
package com.example.yannews;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
// URL Address
String url = "http://www.yan.vn/";
ProgressDialog mProgressDialog;
ListView listview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView)findViewById(R.id.listView1);
// Locate the Buttons in activity_main.xml
Button titlebutton = (Button) findViewById(R.id.titlebutton);
Button descbutton = (Button) findViewById(R.id.descbutton);
// Capture button click
titlebutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Execute Title AsyncTask
new Title().execute();
}
});
// Capture button click
descbutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Execute Description AsyncTask
new Description().execute();
}
});
}
// Title AsyncTask
private class Title extends AsyncTask<Void, Void, Void> {
String title;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Android Basic JSoup Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
// Connect to the web site
Document document = Jsoup.connect(url).get();
// Get the html document title
title = document.title();
System.out.println(title);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//Title get works however,displaying the bunch of information is not working with me.
#Override
protected void onPostExecute(Void result) {
// Set title into TextView
TextView txttitle = (TextView) findViewById(R.id.titletxt);
txttitle.setText(title);
mProgressDialog.dismiss();
}
}
// Description AsyncTask
private class Description extends AsyncTask<Void, Void, ArrayList<String>> {
ArrayList<String> news = new ArrayList<String>();
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Android Basic JSoup Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
The problem is in doInBackGround , the code didn't get information but when I tested on Java project , it completely worked.
#Override
protected ArrayList<String> doInBackground(Void... params)
{
//String desc = "Những ngôi sao trẻ \"giỏi kiếm tiền\" nhất Hollywood";
Document document = null;
try {
document = Jsoup.connect(url).get();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for(Element e : document.select("div[class=dvSubBannerText dvTitle15]"))
{
news.add(e.text());
}
//getString(news);
return news;
}
When debugging, I realized that news didn't contains any information.
#Override
protected void onPostExecute( ArrayList<String> result) {
// Set description into TextView
ArrayAdapter<String>adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,android.R.id.text1);
for (String temp_result : result) {
adapter.add(temp_result);
}
listview.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
// Logo AsyncTask
}
So the question is why I can't display the information I got from website by Jsoup to ListView ?
Anyone can help me with that . I really appreciate.
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