I have a button that gets month and year from spinners then calls an Async task, which read json data. That part works fine But if I try and change the month and year then click the button again it does nothing. I have to press back to reload the page to click the button again to get different results.
Here is my code. Can any of you smart folks please help me.
package com.app.simplictyPortal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.app.simplicityPortal.adapter.InvoiceAdapter;
import android.app.Fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
public class InvoiceFragment extends Fragment {
public InvoiceFragment(){}
Button load;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_invoice, container, false);
ArrayList<String> years = new ArrayList<String>();
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
int currentMonth = Calendar.getInstance().get(Calendar.MONTH);
for (int i = 2013; i <= thisYear; i++)
{
years.add(Integer.toString(i));
}
//String tmonth = Integer.toString(currentMonth);
String tyear = Integer.toString(thisYear);
final Spinner year = (Spinner)rootView.findViewById(R.id.spinner1);
final Spinner month = (Spinner)rootView.findViewById(R.id.spinner2);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, years);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
year.setAdapter(adapter);
year.setSelection(adapter.getPosition(tyear));
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(getActivity(),
R.array.month, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
month.setAdapter(adapter2);
month.setSelection(currentMonth);
load=(Button)rootView.findViewById(R.id.button1);
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String y = (String) year.getSelectedItem();
int im = month.getSelectedItemPosition();
String m = Integer.toString(im +1);
final GlobalClass globalVariable = (GlobalClass) getActivity().getApplicationContext();
final String Compid = globalVariable.getCompid();
new InvoiceAsyncTask().execute("http://dev-sql1:8080/api/invoice/getall/"+Compid+"?m="+m+"&y="+y);
}
});
return rootView;
}
public void invoice(JSONArray jArray) {
ListView lv = (ListView) getView().findViewById(R.id.listView1);
List<ListViewItem> items = new ArrayList<InvoiceFragment.ListViewItem>();
try {
for (int i = 0; i <jArray.length(); i++) {
final JSONObject json_data = jArray.getJSONObject(i);
items.add(new ListViewItem()
{{
Vendor= json_data.optString("CarrierName");
Bill = "$ " + json_data.optString("BillAmount");
Serviceacct = json_data.optString("ServiceAccountNumber");
Date = json_data.optString("ReceivedDate");
}});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InvoiceAdapter adapter = new InvoiceAdapter(getActivity(), items);
lv.setAdapter(adapter);
// TODO Auto-generated method stub
}
public class ListViewItem
{
public String Vendor;
public String Bill;
public String Serviceacct;
public String Date;
} public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public class InvoiceAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
invoice(jArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
How do you process results of your InvoiceAsyncTask? Do you implement a callback from your AsyncTask's onPostExecute() to the activity?
Maybe the sample below will help you.
First, implement AsyncTask class with callback interface:
public class ServerRequestAsyncTask extends AsyncTask<String, Void, ServerResponseDetails> {
public ServerRequestAsyncTask(Fragment fragment, ServerRequestDetails request) {
mFragment = fragment;
mRequest = request;
}
public interface OnServerRequestAsyncTaskCompletedListener {
void onServerRequestAsyncTaskCompleted(ServerResponseDetails response);
}
public void cancel() {
if (mHttpGet != null && !mHttpGet.isAborted()) mHttpGet.abort();
cancel(true);
}
And also add onPostExecute():
#Override
protected void onPostExecute(ServerResponseDetails response) {
if (mFragment != null) mFragment.onServerRequestAsyncTaskCompleted(response);
}
I call AsyncTask from Fragment, but you can use it with Activity instead.
Then, in your Activity you implement interface:
#Override
public void onServerRequestAsyncTaskCompleted(ServerResponseDetails response) {
// do what you need here, then 'finish' task by setting mServerRequest to null
mServerRequest = null;
}
And to execute AsyncTask:
protected ServerRequestAsyncTask mServerRequest = null;
public boolean isServerRequestRunning() {
return (mServerRequest != null);
}
public void cancelServerRequest() {
mServerRequest.cancel();
}
public void sendServerRequest(Fragment fragment, ServerRequestDetails request) {
if (Application.isNetworkAvailable()) {
if (!isServerRequestRunning()) {
mServerRequest = new ServerRequestAsyncTask(fragment, request);
mServerRequest.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
{params});
}
}
}
mServerRequest variable holds reference to currently executed task. You can call mServerRequest.cancel() if need to abort.
Thanks Everyone But I have figured it out. I needed to cancel the Async task in the post execute method.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
invoice(jArray);
cancel(true);
isCancelled();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Related
I have a news app. My app takes so much time to fetch data from server and display it on the listView.But i have seen that apps like flipboard,facebook and Game News which has more data to fetch than mine does it faster.I think my app loads the entire data and displays the entire list together.Is there a way to display the list such that it loads the items in listView one by one?I do the fetching using a AsyncTaskLoader in the background.Also how to display a large list of news like 100 in a list .
MainActivity:
package com.example.android.gametalks;
import android.app.LoaderManager;
import android.content.Intent;
import android.content.Loader;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<GameNews>> {
//IGN url
final String ign_url = "https://newsapi.org/v1/articles?source=ign&sortBy=top&apiKey=679f6fb918d34343b18590ca70f7fcde";
final String google_url = " https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=679f6fb918d34343b18590ca70f7fcde";
final String engadget_url = "https://newsapi.org/v1/articles?source=engadget&sortBy=top&apiKey=679f6fb918d34343b18590ca70f7fcde";
GameAdapter adapter ;
private View progressBar;
final private int game_loader = 0;
ArrayList<String> urls = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
urls.add(ign_url);
urls.add(google_url);
urls.add(engadget_url);
//Getting listView
ListView gameListView = (ListView) findViewById(R.id.listView);
//progress bar finding
progressBar = findViewById(R.id.progress_bar);
ArrayList<GameNews> gameList = new ArrayList<>();
//Making a new arrayAdapter
adapter = new GameAdapter(this,gameList);
//Connecting ArrayAdapter to ListView
gameListView.setAdapter(adapter);
getLoaderManager().initLoader(game_loader, null, this);
//ListView item click listner
gameListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
GameNews currentEarthquake = adapter.getItem(i);
String url = currentEarthquake.getUrl();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
}
#Override
public Loader<List<GameNews>> onCreateLoader(int i, Bundle bundle) {
return new GameLoader(this,urls);
}
#Override
public void onLoadFinished(Loader<List<GameNews>> loader, List<GameNews> games) {
progressBar.setVisibility(View.INVISIBLE);
adapter.clear();
if(games == null)
{
return;
}
adapter.addAll(games);
}
#Override
public void onLoaderReset(Loader<List<GameNews>> loader) {
adapter.clear();
}
}
GameLoader:
package com.example.android.gametalks;
import android.content.AsyncTaskLoader;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
/**
* Created by apple on 9/8/17.
*/
public class GameLoader extends AsyncTaskLoader<List<GameNews>> {
private ArrayList<String> Urls = new ArrayList<>();
public GameLoader(Context context, ArrayList<String> Url) {
super(context);
Urls = Url;
}
#Override
protected void onStartLoading()
{
forceLoad();
}
#Override
public List<GameNews> loadInBackground() {
if(Urls == null)
{
return null;
}
// Perform the HTTP request for earthquake data and process the response.
List<GameNews> games = QueryUtils.FetchEarthquakeData(Urls);
return games;
}
}
QueryUtils(Here the network fetching takes place):
package com.example.android.gametalks;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ListView;
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.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Helper methods related to requesting and receiving earthquake data from USGS.
*/
public final class QueryUtils {
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
/**
* Create a private constructor because no one should ever create a {#link QueryUtils} object.
* This class is only meant to hold static variables and methods, which can be accessed
* directly from the class name QueryUtils (and an object instance of QueryUtils is not needed).
*/
private QueryUtils() {
}
public static List<GameNews> FetchEarthquakeData(ArrayList<String> Url) {
List<GameNews> games ;
List<GameNews> Total = new ArrayList<>();
URL url;
Log.d(LOG_TAG,Url.get(0));
for(int i = 0 ; i < Url.size(); i++) {
url = createUrl(Url.get(i));
try {
//Make http request
String jsonResponse = makeHttpRequest(url);
games = extractFeatureFromJson(jsonResponse);
Total.addAll(games);
} catch (IOException e) {
Log.e("IOException", "" + e);
}
}
return Total;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error with creating URL ", e);
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readInputStream(inputStream);
} else {
Log.e(LOG_TAG, "" + urlConnection.getResponseCode());
return null;
}
} catch (IOException e) {
Log.d(LOG_TAG, "" + e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// function must handle java.io.IOException here
inputStream.close();
}
}
return jsonResponse;
}
private static String readInputStream(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();
}
private static ArrayList<GameNews> extractFeatureFromJson(String jsonResponse) {
ArrayList<GameNews> games = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray articles = jsonObject.getJSONArray("articles");
for (int i = 0; i < articles.length(); i++) {
JSONObject currentGame = articles.getJSONObject(i);
// Extract the value for the key called "mag"
String title = currentGame.getString("title");
// Extract the value for the key called "place"
String description = currentGame.getString("description");
// Extract the value for the key called "url"
String url = currentGame.getString("url");
//Extract value from key called urlToImage
String urlToImage = "nn";
urlToImage = currentGame.getString("urlToImage");
URL urlOfImage = null;
Bitmap bmp = null;
try {
urlOfImage = new URL(urlToImage);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
bmp = BitmapFactory.decodeStream(urlOfImage.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
// Create a new {#link Earthquake} object with the magnitude, location, time,
// and url from the JSON response.
GameNews game = new GameNews(title, description,bmp,url);
// Add the new {#link Earthquake} to the list of earthquakes.
games.add(game);
}
} catch (JSONException e) {
Log.d(LOG_TAG, "" + e);
}
return games;
}
}
Thanks in advance.
I am with a problem in my code . I tried many things in this code , However it does not fix . In the end the error is described. It is something related with constructor.
SelectActivityAnswer.java
package com.example.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class SelectAnswerActivity extends Fragment {
final static String ARG_POSITION_ANSWER = "position";
private String jsonResult;
private String url = "http://myip/employee_details.php";
private ListView listView;
public SelectAnswerActivity() {
// Empty constructor required for fragment subclasses
}
//#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//SimpleAdapter simpleAdapter = new SimpleAdapter(this, null, 0, null, null);
View rootView = inflater.inflate(R.layout.activity_select_answer, container, false);
accessWebService();
// selectListAns = (ListView) rootView.findViewById(R.id.ans_list);
// novo code abaixo
// ListAdapterAns adapterAns = new ListAdapterAns(this,toppings);
// selectListAns.setAdapter(adapterAns);
// selectListAns.setOnItemClickListener(new AnsItemClickListener());
//View rootView = inflater.inflate(R.layout.activity_select_answer, container, false);
//int i = getArguments().getInt(ARG_PLANET_NUMBER);
//String planet = getResources().getStringArray(R.array.planets_array)[i];
//int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
// "drawable", getActivity().getPackageName());
// ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
// getActivity().setTitle(planet);
return rootView;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
//Toast.makeText(getApplicationContext(),
// "Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("employee name");
String number = jsonChildNode.optString("employee no");
String outPut = name + "-" + number;
employeeList.add(createEmployee("employees", outPut));
}
} catch (JSONException e) {
//Toast.makeText(getApplicationContext(), "Error" + e.toString(),
// Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
R.id.content_list_ans,
new String[] { "employees" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
//Toast.makeText(getApplication(), "c", Toast.LENGTH_SHORT).show();
}
private HashMap<String, String> createEmployee(String name, String number) {
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
}
The line is:
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
R.id.content_list_ans,
new String[] { "employees" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
The error is :
The constructor SimpleAdapter(SelectAnswerActivity, List<Map<String,String>>, int, String[], int[]) is
undefined.
Is the problem this(context) ?
Try this, using Activity context instead of Fragment
SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(), employeeList,
R.id.content_list_ans,
new String[] { "employees" }, new int[] { android.R.id.text1 });
Your reference to the Context is wrong. You cannot have the activity context in the AsynTask class. You should try one of getApplicationContext() or getActivity() instead of this.
Also SelectAnswerActivity is not and Activity, its a Fragment. If it was activity you could have also used SelectAnswerActivity.this
You are referencing the context of the fragment, not the one of your Activity. Try changing that.
Here is my java code for loading a title, description, date and an image from Mysql through Php in a loop. Everything loading perfectly except image. When I load image the loading dialog box displaying and I can see only one image in the background but the loading dialogue box is still appearing. I'm new in android so I need experts help like you.
JAVA
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Dialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class News_events extends Fragment {
private String jsonResult;
private String url = "http://192.168.2.7/crescentnews/select.php";
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
ImageView img;
Bitmap bitmap;
ProgressDialog pDialog;
InputStream is=null;
String result=null;
String line=null;
int code;
public News_events(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news_events, container, false);
accessWebService();
return rootView;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
display();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void display() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news_details");
LinearLayout MainLL= (LinearLayout)getActivity().findViewById(R.id.newslayout);
//LinearLayout headLN=(LinearLayout)findViewById(R.id.headsection);
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
final String head = jsonChildNode.optString("title");
final String details = jsonChildNode.optString("text");
final String date = jsonChildNode.optString("date");
final String image = jsonChildNode.optString("img");
//final String time = jsonChildNode.optString("time");
//img = new ImageView(this.getActivity());
//new LoadImage().execute("http://192.168.2.7/crescentnews/images/"+image);
img = new ImageView(this.getActivity());
LoadImage ldimg=new LoadImage();
ldimg.setImage(img);
ldimg.execute("http://192.168.2.7/crescentnews/images/"+image);
TextView headln = new TextView(this.getActivity());
headln.setText(head); // News Headlines
headln.setTextSize(20);
headln.setTextColor(Color.BLACK);
headln.setGravity(Gravity.CENTER);
headln.setBackgroundResource(R.drawable.menubg);
headln.setPadding(10, 20, 10, 0);
headln.setWidth(100);
headln.setClickable(true);
headln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), head, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity().getApplicationContext(),MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
ImageView photo=new ImageView(this.getActivity());
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
photo.setBackgroundColor(Color.parseColor("#000000"));
photo.setPadding(0, 0, 10, 10);
photo.setClickable(true);
// Drawable drawable = LoadImageFromWebOperations("http://192.168.2.7/crescentnews/images/"+pic);
// userpic.setImageDrawable(drawable);
TextView dateln = new TextView(this.getActivity());
dateln.setText(date); // News Headlines
dateln.setTextSize(12);
dateln.setTextColor(Color.BLACK);
dateln.setGravity(Gravity.RIGHT);
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
dateln.setBackgroundColor(0x00000000);
dateln.setPadding(0, 0, 10, 10);
dateln.setWidth(100);
dateln.setClickable(true);
dateln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
View sep=new View(this.getActivity());
sep.setBackgroundColor(Color.parseColor("#252525"));
sep.setMinimumHeight(10);
TextView detailsln = new TextView(this.getActivity());
detailsln.setText(details); // News Details
detailsln.setTextSize(12);
detailsln.setTextColor(Color.BLACK);
detailsln.setGravity(Gravity.LEFT);
detailsln.setPadding(10, 10, 10, 10);
MainLL.addView(headln);
MainLL.addView(dateln);
MainLL.addView(photo);
MainLL.addView(img);
MainLL.addView(detailsln);
MainLL.addView(sep);
detailsln.setClickable(true);
detailsln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
}
} catch (JSONException e) {
Toast.makeText(getActivity().getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
public void setImage(ImageView img ){
this.img=img;
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
}
catch (Exception e) { e.printStackTrace(); }
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
pDialog = new ProgressDialog(getActivity());
pDialog.dismiss();
}
pDialog.dismiss();
}
}
your code seems to be ok.
also check some option like volley
Try something like following
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
public void setImage(ImageView img ){
this.img=img;
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
}
pDialog.dismiss();
}
}
To call this
img = new ImageView(this.getActivity());
LoadImage ldimg=new LoadImage();
ldimg.setImage(img);
ldimg.execute("http://192.168.2.7/crescentnews/images/"+image);
To dismiss dialog show the dialog only once before for loop and dismiss it after for loop
Hope it will help :)
I have an app I am trying to pass data through an ASYNC task but am getting a null pointer error in my onPosteExecute method. Seems like no matter how I change my code I still get this same fatal error:
10-31 18:43:56.517 1253-1253/com.brianstacks.project1 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.brianstacks.project1, PID: 1253
java.lang.NullPointerException
at com.brianstacks.project1.MainActivity$MyTask.onPostExecute(MainActivity.java:277)
at com.brianstacks.project1.MainActivity$MyTask.onPostExecute(MainActivity.java:247)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Here is my code:
MainActivity.java
public class MainActivity extends ListActivity implements MasterFragment.OnListItemClickListener {
final String Tag = "Project 1 test";
EditText myEdit;
Button myButton;
ProgressBar pb;
SerialCustomObject myObject;
// create a reference to the list's needed for data
List<MyTask> tasks;
ArrayList<Places> placeList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if ((savedInstanceState != null)&& (savedInstanceState.getSerializable("name") != null)) {
Places name = (Places) savedInstanceState.getSerializable("name");
Log.v("name:",name.getName());
}
//initiate my tasks
tasks = new ArrayList<>();
pb = (ProgressBar)findViewById(R.id.progressBar);
myEdit = (EditText)findViewById(R.id.myEditText);
myButton = (Button)findViewById(R.id.myButton);
}
#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 boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
public void findAndRemoveFragment() {
FragmentManager mgr = getFragmentManager();
DetailFragment frag =
(DetailFragment) mgr.findFragmentByTag(DetailFragment.TAG);
if (frag == null) {
// No fragment found, possibly because the transaction
// hasn't completed yet.
} else {
// Fragment found. You can use it here.
FragmentTransaction trans = mgr.beginTransaction();
trans.remove(frag);
trans.commit();
// When the main thread runs, the fragment will be
// removed from the activity.
}
}
public void deviceStorage() {
// Read in a private file
try {
FileInputStream fis = this.openFileInput("some_file.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Create new or open existing private file
try {
FileOutputStream fos = this.openFileOutput("some_other_file.txt", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void writeToFile(Context _c, String _filename, String _data) {
File external = _c.getExternalFilesDir(null);
File file = new File(external, _filename);
try {
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
if(myObject == null) {
myObject = new SerialCustomObject();
}
myObject.setData(_data);
oos.writeObject(myObject);
oos.close();
// Write bytes to the stream
fos.write(_data.getBytes());
// Close the stream to save the file.
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private String readFromFile(String _filename) {
File external = getExternalFilesDir(null);
File file = new File(external, _filename);
try {
FileInputStream fin = new FileInputStream(file);
InputStreamReader inReader = new InputStreamReader(fin);
BufferedReader reader = new BufferedReader(inReader);
// Reading data from our file using the reader
// and storing it our string buffer.
StringBuffer buffer = new StringBuffer();
String text = null;
// Make sure a line of text is available to be read.
while((text = reader.readLine()) != null) {
buffer.append(text + "\n");
}
// Close the reader and underlying stream.
reader.close();
// Convert the buffer to a string.
return buffer.toString();
} catch(IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public void displayText(String myText) {
DetailFragment frag = (DetailFragment) getFragmentManager().findFragmentByTag(DetailFragment.TAG);
if (frag == null){
frag = DetailFragment.newInstance(myText);
getFragmentManager().beginTransaction()
.replace(R.id.container2,frag,DetailFragment.TAG)
.commit();
}else {
frag.setDisplayInfo(myText);
}
}
//#Override
public void onClick(View _v){
myEdit = (EditText)findViewById(R.id.myEditText);
String newString = myEdit.getText().toString();
Log.v(Tag,newString);
}
// the method for when the button is clicked
public void myClick(View _v){
// create a string to grab the text of the edit text
String myString = myEdit.getText().toString();
// replace the spaces with + to encode into the url
String encodedString = myString.replace(" ","+");
//check to see if online and if so continue to get the JSON data if not toast a message telling the user no connection
if (isOnline()){
requestData("https://maps.googleapis.com/maps/api/place/textsearch/json?query="+encodedString+"&key=AIzaSyB9iOw6wF4FwbOdUTZYiU_MxsbfWM5iMOI");
}else Toast.makeText(this, "Network isn't available", Toast.LENGTH_SHORT).show();
}
// method to get the data from ASYNC task
private void requestData(String uri) {
MyTask task = new MyTask();
task.execute(uri);
}
// method to check internet connectivity
protected boolean isOnline(){
ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
protected void updateDisplay(ArrayList<Places> placeList){
// get instance of the Master List fragment then replaces container1 and commits it to the activity
MasterFragment frag = MasterFragment.newInstance(placeList);
getFragmentManager().beginTransaction()
.replace(R.id.container1, frag, MasterFragment.TAG).commit();
}
// Async task method to do network action in
private class MyTask extends AsyncTask<String ,String ,String>{
#Override
protected void onPreExecute() {
// add this to the task
tasks.add(this);
}
#Override
protected String doInBackground(String... params) {
return HttpManager.getData(params[0]);
}
#Override
protected void onPostExecute(String result) {
tasks.remove(this);
if(null != result && !result.isEmpty()) {
placeList = JSONParser.parseFeed(result);
updateDisplay(placeList);
}else {
Toast.makeText(MainActivity.this, "Can't connect to API", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onProgressUpdate(String... values) {
}
}
}
DetailFragment.java
package com.brianstacks.project1.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.brianstacks.project1.R;
/**
* Created by Brian Stacks
* on 10/27/14
* for FullSail.edu.
*/
public class DetailFragment extends Fragment {
public static final String TAG = "DetailFragment.TAG";
public static final String ARG_TAG = "DetailFragment.TAG";
public static DetailFragment newInstance(String myString) {
DetailFragment frag = new DetailFragment();
Bundle args = new Bundle();
args.putString(ARG_TAG, myString);
frag.setArguments(args);
return frag;
}
#Override
public View onCreateView(LayoutInflater _inflater, ViewGroup _container,
Bundle _savedInstanceState) {
// Create and return view for this fragment.
return _inflater.inflate(R.layout.detail_layout, _container, false);
}
#Override
public void onActivityCreated(Bundle _savedInstanceState) {
super.onActivityCreated(_savedInstanceState);
Bundle args = getArguments();
if(args != null && args.containsKey(ARG_TAG)){
setDisplayInfo(args.getString(ARG_TAG));
}
}
public void setDisplayInfo(String myText){
getArguments().putString(ARG_TAG,myText);
// Get our TextView and set some text to it.
TextView tv;
tv = (TextView)getView().findViewById(R.id.detailText);
tv.setText(myText);
}
}
MasterFragment.java
package com.brianstacks.project1.fragments;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListFragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.brianstacks.project1.JSONParser;
import com.brianstacks.project1.MainActivity;
import com.brianstacks.project1.Places;
import com.brianstacks.project1.PlacesAdapter;
import com.brianstacks.project1.R;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Brian Stacks
* on 10/27/14
* for FullSail.edu.
*/
public class MasterFragment extends ListFragment{
public static final String TAG = "MasterFragment.TAG";
public static final String KEY = "places";
private OnListItemClickListener mListener;
private ArrayList<Places> placeList2;
public static MasterFragment newInstance(ArrayList<Places> placeList) {
MasterFragment masterFragment = new MasterFragment();
Bundle args = new Bundle();
args.putSerializable("places", placeList);
masterFragment.setArguments(args);
return masterFragment;
}
public interface OnListItemClickListener{
public void displayText(String myText);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
if (activity instanceof OnListItemClickListener){
mListener = (OnListItemClickListener) activity;
}else {
throw new IllegalArgumentException("Containing Activity must implement the OnListItemClicked");
}
}
#Override
public void onActivityCreated(Bundle _savedInstanceState) {
super.onActivityCreated(_savedInstanceState);
if (_savedInstanceState == null){
Bundle args = getArguments();
String myStrings=args.getString("places");
Log.v("Places",myStrings);
/*String[] presidents = getResources().getStringArray(R.array.presidents);
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, presidents);
//PlacesAdapter adapter2 = new PlacesAdapter(this.getActivity(),R.layout.item_place,placeList);
//setListAdapter(adapter2);
}
#Override
public void onListItemClick(ListView _l, View _v, int _position, long _id) {
String president = (String)_l.getItemAtPosition(_position);
mListener.displayText(president);
*/
}
}
}
HTTPManager.java
package com.brianstacks.project1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Brian Stacks
* on 10/20/14
* for FullSail.edu.
*/
public class HttpManager {
public static String getData(String uri){
BufferedReader reader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null){
sb.append(line).append("");
}
return sb.toString();
}catch (Exception e){
e.printStackTrace();
return null;
}finally {
if (reader!=null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
JSONParser.java
package com.brianstacks.project1;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Brian Stacks
* on 10/20/14
* for FullSail.edu.
*/
public class JSONParser {
public static ArrayList<Places> parseFeed(String content) {
JSONObject myObj;
try {
myObj = new JSONObject(content);
JSONArray result = myObj.getJSONArray("results");
ArrayList<Places> placeList = new ArrayList<>();
for (int i = 0; i < result.length(); i++) {
JSONObject obj = result.getJSONObject(i);
Places place = new Places();
place.setName(obj.getString("name"));
place.setFormatted_address(obj.getString("formatted_address"));
place.setTypes(obj.getString("types"));
//place.setPhotos(obj.getString("photos"));
placeList.add(place);
}
return placeList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}
Places.java
import java.io.Serializable;
/**
* Created by Brian Stacks
* on 10/22/14
* for FullSail.edu.
*/
public class Places implements Serializable {
private String pName;
private String pTypes;
private String pFormatted_address;
public Places(){
pName ="";
pTypes ="";
pFormatted_address = "";
}
public String getName() {
return pName;
}
public void setName(String name) {
pName = name;
}
public String getTypes() {
return pTypes;
}
public void setTypes(String types) {
pTypes= types;
}
public String getFormatted_address() {
return pFormatted_address;
}
public void setFormatted_address(String formatted_address) {
pFormatted_address=formatted_address;
}
}
Any help is much appreciated
ALSO was reading this post but to no avail LINK!
I found my solution to this problem, it was I was trying to cast my Objectin my MasterFragment.java as a String when the code was expecting an ArrayList<Places> changed that bit of code and pow there it was, no error.
Old Code
Bundle args = getArguments();
String myStrings=args.getString("places");
New Code
Bundle args = getArguments();
ArrayList myStrings = args.getParcelableArrayList("places");
Dear Stackoverflow Comunitiy,
I'd like to have a ListView getting filled by an BackgroundTask.
This is my actual Code
HomeActivity:
package com.example.instaemgnew;
import java.util.ArrayList;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import com.example.instaemgnew.classes.Beitrag;
import com.example.instaemgnew.classes.beitragLoader;
import com.example.instaemgnew.classes.listViewHomeActivitiyAdapter;
public class HomeActivity extends ListActivity {
listViewHomeActivitiyAdapter adapter;
ArrayList<Beitrag> beitraege = new ArrayList<Beitrag>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
adapter = new listViewHomeActivitiyAdapter(this, beitraege);
setListAdapter(adapter);
Log.e("TestPoint 1", "Adapter Set");
new beitragLoader(this).execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_home, menu);
return true;
}
public void addToListView(Beitrag toAddBeitrag){
beitraege.add(toAddBeitrag);
adapter.notifyDataSetChanged();
}
}
BackgroundTask:
package com.example.instaemgnew.classes;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.instaemgnew.HomeActivity;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.ArrayAdapter;
public class beitragLoader extends AsyncTask<String, String, String>{
//Array List für die Beiträge
ArrayList<Beitrag> beitraege;
//User Daten
/*mail = userManager.getMail();
grade = String.valueOf(userManager.getGrade());
school = userManager.getSchool();*/
String mail = "simon-frey#gmx.de";
String grade = String.valueOf(334);
String school = "EMG";
//JSONParser
JSONParser jsonParser = new JSONParser();
//ArrayList mit Beitrag Objekten
ArrayList<Beitrag> beitraegeList;
// Onlinedaten
private static final String SERVER_URL = "http://yooui.de/InstaEMGTest/";
private static final String PASSWORD = "8615daf406f7e2b313494f0240";
//Context
private final HomeActivity homeActivity;
//Konstruktor
public beitragLoader(HomeActivity homeActivity){
this.homeActivity = homeActivity;
Log.e("TestPoint 2", "Created beitragLoader");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//TODO: Test for InternetConnection
Log.e("TestPoint 3", "PreExectute");
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
beitraegeList = new ArrayList<Beitrag>();
String SQLUrl = SERVER_URL + "testBeiträgeAbrufen.php";
String token = getMD5Hash("password" + "data");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("token", token));
//TODO: params.add(new BasicNameValuePair("page", skipBeitraege))
params.add(new BasicNameValuePair("grade", grade));
params.add(new BasicNameValuePair("school", school));
JSONObject json = jsonParser.makeHttpRequest(SQLUrl, "GET", params);
if (json == null) {
// Server offline
}
Log.e("TestPoint 3,5", "FetchedJSON");
try {
JSONArray beitraege = json.getJSONArray("beitraege");
// looping through All Products
for (int i = 0; i < beitraege.length(); i++) {
Beitrag tempBeitrag = null;
Log.e("TestPoint 3,6", "StartLoop");
JSONObject c = beitraege.getJSONObject(i);
//HDImagesURLList ArrayList
ArrayList<String> HDImagesURLList = new ArrayList<String>();
// Storing each json item in variable
String id = c.getString("ID");
String url = c.getString("url");
String titel = c.getString("titel");
String tags = c.getString("tags");
String onlineDate = c.getString("onlineDate");
Log.e("TestPoint 3,7", "Stored JSON Items");
//Fetching previewImage
try {
Log.e("TestPoint 3,8", "TryImageDownload");
InputStream in = new java.net.URL(url).openStream();
String fileName = "InstaEMG" + String.valueOf(System.currentTimeMillis())+".jpg";
Log.e("imageUri", url);
Log.e("fileName", fileName);
FileOutputStream fileOutput = new FileOutputStream(new File(Environment.getExternalStorageDirectory(),fileName));
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = in.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
Log.e("File Output", String.valueOf(bufferLength));
}
//Fill HDImagesURLList
//TODO
// creating newBeitrag
tempBeitrag = new Beitrag(Integer.parseInt(id), titel, onlineDate, fileName, HDImagesURLList);
// adding Beitrag to ArrayList
beitraegeList.add(tempBeitrag);
Log.e("TestPoint 4", "NewBeitragSet");
} catch (MalformedURLException e) {
Log.e("Exceptrion", "URL Exception");
} catch (IOException e) {
Log.e("Exceptrion", "IO Exception");
}
homeActivity.addToListView(tempBeitrag);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return null;
}
/**
* After completing background Safe to MainActivity
* **/
protected void onPostExecute() {
Log.e("TestPoint 5", "PostExecutre");
// homeActivity.updateListView(beitraegeList);
}
/**
* Methode zum Errechnen eines MD5Hashs
*
* #param string
* String welcher kodiert werden soll
* #return MD5 Hash des Strings, bei Fehler der ursprüngliche String.
*/
private String getMD5Hash(String string) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(string.getBytes());
byte[] result = md5.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < result.length; i++) {
if ((0xff & result[i]) < 0x10) {
hexString.append("0" + Integer.toHexString((0xFF & result[i])));
} else {
hexString.append(Integer.toHexString(0xFF & result[i]));
}
}
string = hexString.toString();
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
return string;
};
}
and the BaseAdapter:
package com.example.instaemgnew.classes;
import java.util.ArrayList;
import com.example.instaemgnew.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class listViewHomeActivitiyAdapter extends BaseAdapter {
private final Context context;
private ArrayList<Beitrag> beitraege;
private final LayoutInflater layoutInflater;
public listViewHomeActivitiyAdapter(Context context, ArrayList<Beitrag> beitraege) {
super();
this.beitraege = beitraege;
this.context = context;
this.layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
//Allgemeien Layout Vorgaben
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.single_beitrag_row_layout, parent, false);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.single_beitrag_row_layout, null);
}
//getViews
TextView titelView = (TextView) rowView.findViewById(R.id.beitragTitel);
ImageView beitragImageView = (ImageView) rowView.findViewById(R.id.beitragImg);
/*
* TODO: Tags anzeigen und suchen lassen (Wunschfunktion)
* TextView tagsView = (TextView) rowView.findViewById(R.id.beitragTags);
*/
//setTitel From Object
titelView.setText(beitraege.get(position).getTitel());
//setPreviewImage From Object
beitragImageView.setImageBitmap(beitraege.get(position).getPreviewImage());
//setOnClickListener on PreviewImage for PopOutGallery
beitragImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//TODO: PopOut Gallery
}
});
return rowView;
}
#Override
public int getCount() {
return beitraege.size();
}
#Override
public Object getItem(int position) {
return beitraege.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
In my opinion the Bug have to be in the BaseAdapter, but I don't know where it could be.
Sincerly and thankful,
Simon
To fill listView in doInBackground you need to use Handler, or runOnUiThread, because this is not UI thread.
homeActivity.runOnUiThread(new Runnable()
{
public void run()
{
homeActivity.addToListView(tempBeitrag);
}});
adapter = new listViewHomeActivitiyAdapter(this, beitraege);
beitraege is not populated with any data.
Edit:
Instead of calling this from doInbackground. Use a Interface as a call back to the activity and then populate listview.
public void addToListView(Beitrag toAddBeitrag){
beitraege.add(toAddBeitrag);
adapter.notifyDataSetChanged();
}
How do I return a boolean from AsyncTask?
Instead of boolen value its arraylist in your case.
Then use the below and set the adapter your listview
adapter = new listViewHomeActivitiyAdapter(this, beitraege);