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
Related
I am creating this app which shows the latest news, which gets data from
https://newsapi.org/s/india-health-news-api
but it doesn't fetch all the data. Sometimes it just shows all but sometimes it just shows 2 or 3 news. Also, I don't see any log error message. What is the problem?
HealthNews.java
public class HealthNews extends AppCompatActivity {
private ArrayList urlList;
private NewsAdapter mNewsAdapter;
private static final String REQUEST_URL ="https://newsapi.org/v2/top-headlines?country=in&category=health&apiKey=3f7d99cdbb004766892bd239a4c099be";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health_news);
Intent intent = getIntent();
HealthNews.NewsAsyncTask task = new HealthNews.NewsAsyncTask();
task.execute(REQUEST_URL);
urlList = QueryUtils.m;
ListView listView = (ListView)findViewById(R.id.listViewHealthNews);
mNewsAdapter = new NewsAdapter(this, new ArrayList<News>());
listView.setAdapter(mNewsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(getApplicationContext(), ""+ a.get(position), Toast.LENGTH_SHORT).show();
Object url = urlList.get(position);
Uri uri = (Uri) Uri.parse((String) url); // missing 'http://' will cause crashed
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
private class NewsAsyncTask extends AsyncTask<String, Void, ArrayList<News>> {
ProgressDialog p;
#Override
protected ArrayList<News> doInBackground(String... urls) {
if (urls.length < 1 || urls[0] == null) {
return null;
}
ArrayList<News> result = QueryUtils.fetchEarthquakeData(urls[0]);
return result;
//return null;
}
#Override
protected void onPostExecute(ArrayList<News> data) {
mNewsAdapter.clear();
if (data != null && !data.isEmpty()) {
p.hide();
mNewsAdapter.addAll(data);
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
p = new ProgressDialog(HealthNews.this);
p.setMessage("Latest News...");
p.setIndeterminate(false);
p.show();
}
}
}
QueryUtils.java
private static final String LOG_TAG = "";
private QueryUtils(){
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(30000 /* milliseconds */);
urlConnection.setConnectTimeout(60000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
static ArrayList<String> m = new ArrayList<String>();
public static ArrayList<News> extractNews(String SAMPLE_JSON){
if (TextUtils.isEmpty(SAMPLE_JSON)) {
return null;
}
ArrayList<News> news = new ArrayList<News>();
try {
JSONObject jsonObject1 = new JSONObject(SAMPLE_JSON);
JSONArray baseJSONArray = jsonObject1.getJSONArray("articles");
for (int i = 0; i < baseJSONArray.length(); i++) {
JSONObject jsonObject = baseJSONArray.getJSONObject(i);
JSONObject source = jsonObject.getJSONObject("source");
String name = source.getString("name");
String article = jsonObject.getString("title");
String url1 = jsonObject.getString("url");
String img = jsonObject.getString("urlToImage");
URL url = new URL(img);
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
News a = new News(image, article);
news.add(a);
m.add(url1);
}
} catch (JSONException j) {
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return news;
}
public static ArrayList<News> fetchEarthquakeData(String requestUrl) {
URL url = createUrl(requestUrl);
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
ArrayList<News> news = extractNews(jsonResponse);
return news;
}
I went though your code and found some issues.
Some bad practices i found in your code are:
You are adding your urls in separate list with static specifier. Instead of this you should add the url variable in your News model directly. And you can directly retrieve the whole News model inside ListView > setOnItemClickListener.
You are creating Bitmap for all your images. It may cause OOM Exception. You should use any Image loading library instead.
I have fixed that all issues and created working code. Please do required changes which you want at your end.
HealthNews.java
public class HealthNews extends AppCompatActivity {
private Context context;
private NewsAdapter mNewsAdapter;
private ArrayList<News> listNews;
private static final String REQUEST_URL = "https://newsapi.org/v2/top-headlines?country=in&category=health&apiKey=3f7d99cdbb004766892bd239a4c099be";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.health_news);
context = this;
ListView list_news = findViewById(R.id.list_news);
listNews = new ArrayList<>();
mNewsAdapter = new NewsAdapter(context, listNews);
list_news.setAdapter(mNewsAdapter);
list_news.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
News selNews = (News) parent.getAdapter().getItem(position);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(selNews.getUrl())));
} catch (Exception e) {
// Missing 'http://' or 'https://' will cause crash
e.printStackTrace();
}
}
});
new NewsAsyncTask().execute(REQUEST_URL);
}
private class NewsAsyncTask extends AsyncTask<String, Void, ArrayList<News>> {
private ProgressDialog p;
#Override
public void onPreExecute() {
super.onPreExecute();
p = new ProgressDialog(context);
p.setMessage("Latest News...");
p.setIndeterminate(false);
p.show();
}
#Override
public ArrayList<News> doInBackground(String... urls) {
return QueryUtils.fetchEarthquakeData(urls[0]);
}
#Override
public void onPostExecute(ArrayList<News> newsList) {
super.onPostExecute(newsList);
listNews.addAll(newsList);
p.hide();
mNewsAdapter.notifyDataSetChanged();
}
}
}
QueryUtils.java
public class QueryUtils {
public static ArrayList<News> fetchEarthquakeData(String apiUrl) {
ArrayList<News> listNews = new ArrayList<>();
try {
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(30000);
conn.setConnectTimeout(60000);
conn.setRequestMethod("GET");
conn.connect();
int responseCode = conn.getResponseCode();
InputStream iStream;
if (responseCode == HttpURLConnection.HTTP_OK)
iStream = conn.getInputStream();
else
iStream = conn.getErrorStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuilder response = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
response.append(line);
}
String jsonResponse = response.toString();
if (TextUtils.isEmpty(jsonResponse))
return null;
JSONObject jsonObject1 = new JSONObject(jsonResponse);
JSONArray baseJSONArray = jsonObject1.getJSONArray("articles");
for (int i = 0; i < baseJSONArray.length(); i++) {
JSONObject jsonObject = baseJSONArray.getJSONObject(i);
JSONObject source = jsonObject.getJSONObject("source");
News news = new News();
news.setArticle(jsonObject.optString("title"));
news.setUrl(jsonObject.optString("url"));
news.setUrlToImage(jsonObject.optString("urlToImage"));
listNews.add(news);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return listNews;
}
}
News.java (Model)
public class News {
private String article;
private String url;
private String urlToImage;
public News() {
this.article = "";
this.url = "";
this.urlToImage = "";
}
public String getArticle() {
return article;
}
public void setArticle(String article) {
this.article = article;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrlToImage() {
return urlToImage;
}
public void setUrlToImage(String urlToImage) {
this.urlToImage = urlToImage;
}
}
NewsAdapter.java (Change your item layout as per your code)
public class NewsAdapter extends BaseAdapter {
private Context context;
private LayoutInflater mInflater;
private List<News> listNews;
public NewsAdapter(Context context, List<News> listNews) {
this.context = context;
this.listNews = listNews;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return listNews.size();
}
#Override
public News getItem(int position) {
return listNews.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
private ImageView item_img_news;
private TextView item_txt_article;
}
#SuppressLint("InflateParams")
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_news, null);
holder = new ViewHolder();
holder.item_img_news = convertView.findViewById(R.id.item_img_news);
holder.item_txt_article = convertView.findViewById(R.id.item_txt_article);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final News news = getItem(position);
holder.item_txt_article.setText(news.getArticle());
Glide.with(context).load(news.getUrlToImage()).into(holder.item_img_news);
return convertView;
}
}
app > build.gradle
implementation 'com.github.bumptech.glide:glide:4.9.0'
I cannot figure why I getting null listview from it as i tried my url with postman. I think my Android part has some problem with it but i have no idea where the problem.
View Order Activity
public class ViewOrderActivity extends AppCompatActivity {
private ListView listView3;
private CustomAdapter2 listAdapter2;
ArrayList<Order> orderlist = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_order);
User user = SharedPrefManager.getInstance(this).getUser();
String str_oid=String.valueOf(user.getId());
String type="cancel";
BackgroundWorker backgroundWorker=new BackgroundWorker(this);
backgroundWorker.execute(type,str_oid);
listView3 = (ListView) findViewById(R.id.listView3);
getJSON("http://192.168.28.1/restaurant/getorder.php");
}
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
orderlist.add(new Order(obj.getInt("orderid"), obj.getInt("pickuptime"), obj.getInt("pickupdate")));
}
listAdapter2 = new CustomAdapter2(this, orderlist);
listView3.setAdapter(listAdapter2);
}
}
This is custom adapter where the listview is structured.
Custom Adapter
class CustomAdapter2 extends BaseAdapter {
public ArrayList<Order> ordlists;
private Context context;
CustomAdapter2(Context context, ArrayList<Order> ordlists) {
//super(context, R.layout.item_food, strilist);
this.context = context;
this.ordlists = ordlists;
}
#Override
public int getCount(){
return ordlists.size();
}
#Override
public Order getItem(int position){
return ordlists.get(position);
}
#Override
public long getItemId(int position){
return 0;
}
#NonNull
#Override
public View getView(final int position, View convertView, #NonNull ViewGroup parent) {
final ListViewHolder2 listViewHolder2;
View customView2;
if(convertView == null)
{
LayoutInflater menuInflater2 = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// LayoutInflater menuInflater = LayoutInflater.from(getContext());
customView2 = menuInflater2.inflate(R.layout.item_order, parent, false);
listViewHolder2 = new ListViewHolder2();
listViewHolder2.tvorderid = (TextView) customView2.findViewById(R.id.tvorderid );
listViewHolder2.tvtime = (TextView) customView2.findViewById(R.id.tvtime);
listViewHolder2.tvdate = (TextView) customView2.findViewById(R.id.tvdate);
listViewHolder2.btncancel = (Button) customView2.findViewById(R.id.btncancel);
customView2.setTag(listViewHolder2);
}
else
{
customView2=convertView;
listViewHolder2= (ListViewHolder2) customView2.getTag();
}
final Order order=getItem(position);
//Typeface customfont= Typeface.createFromAsset(parent.getContext().getAssets(),"fonts");
listViewHolder2.tvorderid.setText(String.valueOf(order.getOrderid()));
listViewHolder2.tvorderid.setTextColor(Color.YELLOW);
listViewHolder2.tvorderid.setTextSize(10);
listViewHolder2.tvtime.setText(String.valueOf(order.getPickuptime()));
listViewHolder2.tvtime.setTextColor(Color.YELLOW);
listViewHolder2.tvtime.setTextSize(10);
listViewHolder2.tvdate.setText(String.valueOf(order.getPickupdate()));
listViewHolder2.tvdate.setTextColor(Color.YELLOW);
listViewHolder2.tvdate.setTextSize(10);
listViewHolder2.btncancel.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
}
});
return customView2;
}
Background Worker for cancel type
else if (type.equals("cancel")){
try{
String id=params[1];
URL url=new URL(cancel_url);
HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream=httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String post_data= URLEncoder.encode("id","UTF-8")+"="+URLEncoder.encode(id,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream=httpURLConnection.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line=bufferedReader.readLine())!=null){
result+=line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}catch(MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
This is my code for url getorder.php
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$database = "y77";
$conn = new mysqli($hostname, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$orders = array();
session_start();
$id=$_POST["id"];
$stmt =$conn->prepare("SELECT `orderid`, `pickuptime`, `pickupdate` FROM `order` WHERE `id`=$id");
$stmt->execute();
$stmt->bind_result($orderid, $pickuptime, $pickupdate);
while($stmt->fetch()){
$temp = [
'orderid'=>$orderid,
'pickuptime'=>$pickuptime,
'pickupdate'=>$pickupdate
];
array_push($orders, $temp);
}
echo json_encode($orders);
?>
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 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);
}
I am working on my movie project which fetch movie poster from URL, and then putting them into a gridview. I use asynctask to fetch JSON and the parse the url within the json file. However, when I launch my app, the grid is all empty and doing nothing until I rotate my screen or resume my app. Once I rotate my screen or resume my app. It shows all picture. I remove my api key on my code here.
public class FetchMovieTask extends AsyncTask<Void, Void, ArrayList<String>> {
private final String LOG_TAG = FetchMovieTask.class.getSimpleName();
#Override
protected ArrayList<String> doInBackground(Void... params) {
String api_key = "";
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String movieJsonStr = null;
try {
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.authority("api.themoviedb.org")
.appendPath("3")
.appendPath("discover")
.appendPath("movie")
.appendQueryParameter("api_key", api_key);
String myUrl = builder.build().toString();
URL Url = new URL(myUrl);
Log.v(LOG_TAG, myUrl);
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) Url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
movieJsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
movieJsonStr = null;
}
movieJsonStr = buffer.toString();
Log.v("KPN", movieJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
movieJsonStr = null;
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 {
MovieURL = getPosterUrlFromJson(movieJsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
}
private ArrayList<String> getPosterUrlFromJson(String forcastMovieStr)
throws JSONException {
final String OWM_PosterUrl = "poster_path";
final String OWM_releaseDate = "release_date";
final String OWM_overview = "overview";
final String OWM_vote_average = "vote_average";
final String OWM_original_title = "original_title";
final String OWM_results = "results";
JSONObject movieJson = new JSONObject(forcastMovieStr);
JSONArray movieArray = movieJson.getJSONArray(OWM_results);
ArrayList<String> resultStrs = new ArrayList<>();
String posterurl = "http://image.tmdb.org/t/p/w185/";
for (int i = 0; i < movieArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String title;
String overview;
String poster;
// Get the JSON object for movie poster
JSONObject moveposter = movieArray.getJSONObject(i);
poster = moveposter.getString(OWM_PosterUrl);
resultStrs.add(i,posterurl + poster);
}
return resultStrs;
}
protected void onPostExecute(ArrayList<String> strings) {
MovieURL.clear();
for (String s : strings) {
MovieURL.add(s);
}
}
Main:
public class MainActivity extends AppCompatActivity {
public static ArrayList<String> MovieURL = new ArrayList();
public static ImageListAdapter mImageListAdapter;
public GridView gridview;
#Override
protected void onStart() {
super.onStart();
new FetchMovieTask().execute();
mImageListAdapter = new ImageListAdapter(this,MovieURL);
gridview.setAdapter(mImageListAdapter);
gridview.invalidateViews();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridview = (GridView) findViewById(R.id.gridview);
}
private void updateMovieURL(){
new FetchMovieTask().execute();
gridview.invalidateViews();
}
ImagelistAdapter class
public class ImageListAdapter extends ArrayAdapter {
private Context context;
private LayoutInflater inflater;
private ArrayList<String> imageUrls;
public ImageListAdapter(Context context, ArrayList <String> imageUrls) {
super(context, R.layout.image_view, imageUrls);
this.context = context;
this.imageUrls = imageUrls;
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (null == convertView) {
convertView = inflater.inflate(R.layout.image_view, parent, false);
}
Picasso.with(context).load(imageUrls.get(position))
.placeholder(R.drawable.loading)
.into((ImageView) convertView);
return convertView;
}
}
THanks guys
In postExecute do this:
protected void onPostExecute(ArrayList<String> strings) {
MovieURL.clear();
for (String s : strings) {
MovieURL.add(s);
}
mImageListAdapter.notifyDataSetChanged();
}
I found my problem on the asynctask, I didnt override the onPostExecute method. After I override my onPostExecute, I initial my grid view
#Override
protected void onPostExecute(ArrayList<String> strings) {
super.onPostExecute(strings);
mImageListAdapter = new ImageListAdapter(MainActivity.this, MovieURL);
gridview.setAdapter(mImageListAdapter);
}