Android Image Downloader with progress bar and grid view (Android Runtime) - android

I'm new to Java and Android.
Here in this application I'm trying to Download multiple images with progress bar and display images in GridView. I'm not getting any error but some exceptions. When I run this code in eclipse, Emulator Just shows "Unfortunately Stopped". So please can anyone help me to sort out this problem??
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.kailash.imagedownloader/com.kailash.imagedownloader.MainActivity}: java.lang.InstantiationException: can't instantiate class com.kailash.imagedownloader.MainActivity; no empty constructor
newInstance failed: no ()
threadid=1: thread exiting with uncaught exception (group=0x40a13300)
Here's the Code:
package com.kailash.imagedownloader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListAdapter;
public class MainActivity extends Activity{
Button btnShowProgress;
private ProgressDialog pDialog;
GridView grid_view;
public static final int progress_bar_type = 0;
protected static final String[] URLS = {
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_2944.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_2989.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3005.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3012.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3034.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3047.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3092.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3110.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3113.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3128.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3160.jpg",
};
public MainActivity(MainActivity mainActivity) {
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridview = (GridView) findViewById(R.id.grid_view);
gridview.setAdapter((ListAdapter) new MainActivity(this));
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
grid_view = (GridView) findViewById(R.id.grid_view);
btnShowProgress.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new DownloadImages().execute(URLS);
}
});
//new DownloadImages().execute();
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(1000);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public class DownloadImages extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
protected Object doInBackground(Object... params) {
System.out.println("External Storage State = " + Environment.getExternalStorageState());
File directory=new File(Environment.getExternalStorageDirectory(), "/Images");
if (directory.exists()==false)
{
directory.mkdir();
}
for(int i = 0; i <URLS.length; i++) {
try {
File firstFile=new File(directory+"/" +i+ ".jpeg");
if(firstFile.exists()==false)
{
HttpClient httpClient =new DefaultHttpClient();
HttpGet httpGet =new HttpGet(URLS[i]);
HttpResponse resp = httpClient.execute(httpGet);
System.out.println("Status Code = " +resp.getStatusLine().getStatusCode());
if(resp.getStatusLine().getStatusCode()==200)
{
HttpEntity entity = resp.getEntity();
InputStream is = entity.getContent();
Boolean status = firstFile.createNewFile();
FileOutputStream foutS = new FileOutputStream(firstFile);
byte[] buffer = new byte[1024];
long total = 0;
int count;
while((count = is.read(buffer)) != -1){
total += count;
foutS.write(buffer, 0, count);
}
foutS.close();
is.close();
publishProgress(i);
}
}
}catch(MalformedURLException e){
e.printStackTrace();
}catch(ClientProtocolException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#SuppressWarnings("unchecked")
protected void onProgressUpdate(Object... values){
super.onProgressUpdate(values);
}
protected void onPostExecute(String file_url) {
dismissDialog(progress_bar_type);
String imagePath = Environment.getExternalStorageDirectory().toString() + "/Images";
grid_view.setBackgroundDrawable(Drawable.createFromPath(imagePath));
}
}
}
Thank You *please help*

java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.kailash.imagedownloader/com.kailash.imagedownloader.MainActivity}:
java.lang.InstantiationException: can't instantiate class
com.kailash.imagedownloader.MainActivity; no empty constructor
You should not create a constructor when extending Activity. As the system invokes the empty constructor, and creating another one causes the class to not have an empty constructor.
There is also no need to create one, as you shouldn't instantiate an activity by yourself at all. For some reason you instantiate your activity inside onCreate and cast it to ListAdapter, which is an error:
gridview.setAdapter((ListAdapter) new MainActivity(this));
You should use a different class which extends ListAdapter for this.

Related

Array overwrites instead of adding

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.

When i click a list item i want to store it name in an edittext

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 !!!

MainActvity not getting updated when App is first launched

I am developing a MovieApp which loads movie posters in MainActivity Fragment using AsyncTask background thread. I am using gridview and BaseAdapter to display images. Following is the code.
MainActivityFragment.java :
package com.android.example.cinemaapp.app;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
public class MainActivityFragment extends Fragment{
MoviePosterAdapter moviePosterAdapter;
GridView posterGridView;
public HashMap<String, JSONObject> movieMap;
public MainActivityFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onStart(){
super.onStart();
updateMovies();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.moviefragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
updateMovies();
}
return super.onOptionsItemSelected(item);
}
public void updateMovies(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String sortBy = sharedPreferences.getString(getString(R.string.pref_sort_key), getString(R.string.pref_sort_popular));
new FetchMoviePosterTask().execute(sortBy);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
moviePosterAdapter = new MoviePosterAdapter(getActivity());
posterGridView = (GridView) rootView.findViewById(R.id.gridview_movie);
posterGridView.setAdapter(moviePosterAdapter);
posterGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// logic to start detail activity
startActivity(intent);
}
});
return rootView;
}
public class FetchMoviePosterTask extends AsyncTask<String, String, Void> implements Serializable {
#Override
protected Void doInBackground(String... params) {
Log.v("FetchMoviePosterTask", "In background method");
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String movieJsonStr;
try {
//logic to create uri builder
URL url = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
movieJsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
movieJsonStr = null;
}
movieJsonStr = buffer.toString();
// Log.v("MainActivityFragment", "Movie json "+movieJsonStr);
try {
String[] posterPaths = getPosterPaths(movieJsonStr);
for(String path : posterPaths){
publishProgress(path);
}
}catch(JSONException je){
Log.e("MoviePosterPath","Error while parsing JSON");
}
} catch (IOException e) {
Log.e("MoviePosterAdapter", "Error ", e);
movieJsonStr = null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MoviePosterAdapter", "Error closing stream", e);
}
}
}
return null;
}
public String[] getPosterPaths(String movieJsonStr) throws JSONException{
final String POSTER_PATH = //some value
final String POSTER_SIZE = //some value
JSONObject jsonObject = new JSONObject(movieJsonStr);
JSONArray results = jsonObject.getJSONArray("results");
String[] posterStrs = new String[results.length()];
movieMap = new HashMap<String, JSONObject>();
for(int i =0; i < results.length(); i++){
JSONObject movieObj = (JSONObject) results.get(i);
posterStrs[i] = POSTER_PATH + POSTER_SIZE + movieObj.getString("poster_path");
movieMap.put(posterStrs[i], movieObj);
}
return posterStrs;
}
#Override
protected void onProgressUpdate(String... posterValues){
Log.v("FetchMoviePosterTask", "In onProgress method");
moviePosterAdapter.add(posterValues[0]);
super.onProgressUpdate(posterValues);
}
#Override
protected void onPostExecute(Void result) {
Log.v("FetchMoviePosterTask", "In onPostExecute method");
moviePosterAdapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
}
MoviePosterAdapter.java :
package com.android.example.cinemaapp.app;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class MoviePosterAdapter extends BaseAdapter {
ArrayList<String> movieArray = new ArrayList<String>();
private Context mContext;
public MoviePosterAdapter(Context c) {
mContext = c;
}
void add(String path){
movieArray.add(path);
}
void clear(){
movieArray.clear();
}
void remove(int index){
movieArray.remove(index);
}
#Override
public int getCount() {
return movieArray.size();
}
#Override
public Object getItem(int position) {
return movieArray.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
} else {
imageView = (ImageView) convertView;
}
Picasso.with(mContext).load(movieArray.get(position)).into(imageView);
return imageView;
}
}
Problem : When the application is first launched, UI is not getting populated with imageviews. In Logcat I could see control is flowing through doBackground(), onProgressUpdate() and onPostExecute().
When I click 'Refresh' button or If i navigate to some other activity or app and return to Movie app UI (onResume()) it is working perfectly fine. Images are displayed.
Many thanks in advance!
You should change updateMovies(); from onStart() to onCreateView. As Gabe Sechan said, you're wrong about the lifecycle. Try to do some research on the Fragment lifecycle.
Just you need to call method updateMovies(); from onCreateView() after posterGridView = (GridView) rootView.findViewById(R.id.gridview_movie);
remove call from start();

android + json + how to display the extracted data in a list and when it clicked display the data in a single row?

i am creating a simple android app that get data from a webserver in json type and display it in a listView than when i select a row it must display the specified data in a single row but the problem is that the system show an error to the selected item to display it in the other activity.
can anyone help me ???
the error is in the jsonActivityHttpClient class in the onPostExectute method, it do not take the list "finalResult" neither:
new String[] { PLACE_NAME_TAG, LATITUDE_TAG,LONGITUDE_TAG, POSTAL_CODE_TAG }
JSONParserHandler
package com.devleb.jsonparsingactivitydemo;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
public class JSONParserHandler implements ResponseHandler<List<String>> {
public static List<String> finalResult;
public static final String PLACE_NAME_TAG = "placeName";
public static final String LONGITUDE_TAG = "lng";
public static final String LATITUDE_TAG = "lat";
private static final String ADMIN_NAME_TAG = "adminCode3";
public static final String POSTAL_CODE_TAG = "postalcode";
private static final String POSTALCODE = "postalcodes";
#Override
public List<String> handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
// TODO Auto-generated method stub
finalResult = new ArrayList<String>();
String JSONResponse = new BasicResponseHandler()
.handleResponse(response);
try {
JSONObject jsonObject = (JSONObject) new JSONTokener(JSONResponse)
.nextValue();
JSONArray PostalCodes = jsonObject.getJSONArray(POSTALCODE);
for (int i = 0; i < PostalCodes.length(); i++) {
JSONObject postalCode = (JSONObject) PostalCodes.get(i);
String name = postalCode.getString(PLACE_NAME_TAG);
String lat = postalCode.getString(LATITUDE_TAG);
String lng = postalCode.getString(LONGITUDE_TAG);
String postal = postalCode.getString(POSTAL_CODE_TAG);
List<String>tmlResult = new ArrayList<String>();
tmlResult.add(name);
tmlResult.add(lat);
tmlResult.add(lng);
tmlResult.add(postal);
finalResult.addAll(tmlResult);
}
} catch (JSONException E) {
E.printStackTrace();
}
return finalResult;
}
}
JsonActivityHttpClient
package com.devleb.jsonparsingactivitydemo;
import java.io.IOException;
import java.util.List;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import android.app.ListActivity;
import android.content.Intent;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class JsonActivityHttpClient extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new HTTPGetTask().execute();
}
private class HTTPGetTask extends AsyncTask<Void, Void, List<String>> {
private static final String USER_NAME = "devleb";
private static final String URL = "http://api.geonames.org/postalCodeLookupJSON?postalcode=6600&country=AT&username="
+ USER_NAME;
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected List<String> doInBackground(Void... arg0) {
// TODO Auto-generated method stub
HttpGet request = new HttpGet(URL);
JSONParserHandler responseHandler = new JSONParserHandler();
try {
return mClient.execute(request, responseHandler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
if (null != mClient) {
mClient.close();
ListAdapter adapter = new SimpleAdapter(
JsonActivityHttpClient.this, finalResult,
R.layout.list_item, new String[] { PLACE_NAME_TAG, LATITUDE_TAG,
LONGITUDE_TAG, POSTAL_CODE_TAG }, new int[] { R.id.countryname,
R.id.lat, R.id.lng, R.id.postalcode });
setListAdapter(adapter);
}
//setListAdapter(new ArrayAdapter<String>(
// JsonActivityHttpClient.this, R.layout.list_item, result));
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.json_activity_http_client, menu);
return true;
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String place_name = ((TextView) v.findViewById(R.id.countryname)).getText().toString();
String lat = ((TextView) v.findViewById(R.id.lat)).getText().toString();
String lng = ((TextView) v.findViewById(R.id.lng)).getText().toString();
String postal_code = ((TextView) v.findViewById(R.id.postalcode)).getText().toString();
Intent in = new Intent(getBaseContext(), RowItem.class);
in.putExtra(PLACE_NAME_TAG, value)
}
}
MainActivity
package com.devleb.jsonparsingactivitydemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
final #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button bntLoad = (Button) findViewById(R.id.btnload);
bntLoad.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent(getBaseContext(), JsonActivityHttpClient.class));
}
}
RowItem
package com.devleb.jsonparsingactivitydemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class RowItem extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row_item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.row_item, menu);
return true;
}
}
i see 2 problem in your code:
1- you define your AsyncTask class like
AsyncTask<Void, Void, List<String>>
but you get Void on onPostExecute method, so you need change
protected void onPostExecute(Void result)
to
protected void onPostExecute(List<String> result)
2- you try access to finalResult on onPostExecute, bu you define that as static on JSONParserHandler so if you want access that you need :
JSONParserHandler.finalResult
but as you return that on doInBackground method so you can access that with:
result
that you get in onPostExecute.
then you need check result that is equal to null or not, because you return null after catch
your onPostExecute must be like:
protected void onPostExecute(List<String> result) {
// TODO Auto-generated method stub
if (null != mClient) {
mClient.close();
if (result != null)
{
ListAdapter adapter = new SimpleAdapter(
JsonActivityHttpClient.this, result,
R.layout.list_item, new String[] { PLACE_NAME_TAG, LATITUDE_TAG,
LONGITUDE_TAG, POSTAL_CODE_TAG }, new int[] { R.id.countryname,
R.id.lat, R.id.lng, R.id.postalcode });
setListAdapter(adapter);
}
else
// do any thing you want for error happened
}

How to solve empty costume list view issue?

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

Categories

Resources