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);
Related
ElementAdapter class
package com.example.sierendeelementeninbreda;
import android.content.Context;
import android.view.ViewGroup;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class ElementAdapter extends RecyclerView.Adapter<ElementAdapter.ViewHolder> {
private static final String TAG = ElementAdapter.class.getSimpleName();
private List<Element> mElements = new ArrayList<>();
private final ElementOnClickHandler mElementClickHandler;
public ElementAdapter(List<Element> mElements, ElementOnClickHandler mElementClickHandler) {
this.mElements = mElements;
this.mElementClickHandler = mElementClickHandler;
}
#NonNull
#Override
public ElementAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
Log.v(TAG, "++++++++ onCreateViewHolder - viewGroup-class: " + viewGroup.getClass().getSimpleName());
Log.v(TAG, "++++++++ onCreateViewHolder - viewGroup-resourceName: " + viewGroup.getContext().getResources().getResourceName(viewGroup.getId()));
Log.v(TAG, "++++++++ onCreateViewHolder - viewGroup-resourceEntryName: " + viewGroup.getContext().getResources().getResourceEntryName(viewGroup.getId()));
Context context = viewGroup.getContext();
LayoutInflater inflator = LayoutInflater.from(context);
// create a new view
View elementListItem = inflator.inflate(R.layout.element_item, viewGroup, false);
ElementAdapter.ViewHolder viewHolder = new ViewHolder(elementListItem);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Log.v(TAG, "++++ onBindViewHolder-type: " + holder.getClass().getSimpleName());
holder.title.setText(mElements.get(position).getTitle());
holder.geographicalLocation.setText(mElements.get(position).getGeographicalLocation());
holder.identificationNumber.setText(mElements.get(position).getIdentificationNumber());
Picasso.get()
.load(mElements.get(position).getImage())
.into(holder.image);
}
#Override
public int getItemCount() {
return mElements.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//one drinkItem has 3 views
// Provide a reference to each view in the drinkItem
private ImageView image;
private TextView title;
private TextView geographicalLocation;
private TextView identificationNumber;
public ViewHolder(View listItemView) {
super(listItemView);
title = (TextView) listItemView.findViewById(R.id.element_item_name);
geographicalLocation = (TextView) listItemView.findViewById(R.id.element_Location);
identificationNumber = (TextView) listItemView.findViewById(R.id.element_idNumber);
image = (ImageView) listItemView.findViewById(R.id.element_item_imageview);
// image.setOnClickListener(this);
// name.setOnClickListener(this);
// description.setOnClickListener(this);
// listItemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int itemIndex = getAdapterPosition();
mElementClickHandler.onElementClick(view, itemIndex);
}
}
}
NetworkUtils class
package com.example.sierendeelementeninbreda;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Scanner;
public class NetworkUtils extends AsyncTask<String, Void, String> {
private static final String TAG = NetworkUtils.class.getSimpleName();
private OnElementApiListener listener;
private final static String url = "https://services7.arcgis.com/21GdwfcLrnTpiju8/arcgis/rest/services/Sierende_elementen/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json";
public NetworkUtils(OnElementApiListener listener) {
this.listener = listener;
}
#Override
protected String doInBackground(String... input) {
//De methode begint met een log zodat je kunt zien wat er gebeurt in de run.
Log.d(TAG, "doInBackground was called");
String response = null;
HttpURLConnection httpURLConnection = null;
// ToDo: Url maken op basis van internet adres
try {
URL mUrl = new URL(url);
URLConnection mConnection = mUrl.openConnection();
httpURLConnection = (HttpURLConnection) mConnection;
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.connect();
int responseCode = httpURLConnection.getResponseCode();
if(responseCode != HttpURLConnection.HTTP_OK){
Log.e(TAG, "Aanroep naar de server is mislukt!");
} else {
InputStream in = httpURLConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
response = scanner.next();
}
}
Log.d(TAG, response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(httpURLConnection != null)
httpURLConnection.disconnect();
}
return response;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d(TAG, "onPreExecute: ");
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
Log.i(TAG, "createElementFromJson called");
ArrayList<Element> elements = new ArrayList<>();
if (response == null || response.equals("")) {
Log.e(TAG, "onPostExecute: empty response!");
return;
}
try {
JSONObject jsonResults = new JSONObject(response);
JSONArray elementList = jsonResults.getJSONArray("features");
Log.d(TAG, "onPostExecute: " + jsonResults);
Log.i(TAG, "elementArray length = " + elementList.length());
for(int i = 0; i < elementList.length(); i++) {
JSONObject element = elementList.getJSONObject(i);
//all info
JSONObject elementAttributes = element.getJSONObject("attributes");
String image = elementAttributes.getString("URL");
String title = elementAttributes.getString("AANDUIDINGOBJECT");
String geographicalLocation = elementAttributes.getString("GEOGRAFISCHELIGGING");
String identificationNumber = elementAttributes.getString("IDENTIFICATIE");
Element element_item = new Element(title, geographicalLocation, identificationNumber);
element_item.setImage(image);
elements.add(element_item);
Log.i(TAG, String.valueOf(elements.size()));
}
listener.onElementAvailable(elements);
} catch (JSONException e) {
e.printStackTrace();
}
}
public interface OnElementApiListener {
void onElementAvailable(ArrayList<Element> elements);
}
MainActivity class
package com.example.sierendeelementeninbreda;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
implements View.OnClickListener,NetworkUtils.OnElementApiListener,
ElementOnClickHandler{
private static String TAG = MainActivity.class.getName();
private final static String url = "https://services7.arcgis.com/21GdwfcLrnTpiju8/arcgis/rest/services/Sierende_elementen/FeatureServer/0/query?where=1=1&outFields=&outSR=4326&f=json";
private ArrayList<Element> mElementList;
private RecyclerView elementRecyclerView;
private ElementAdapter mElementAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
elementRecyclerView= findViewById(R.id.recyclerView_element_list);
elementRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mElementAdapter = new ElementAdapter(mElementList,this);
elementRecyclerView.setAdapter(mElementAdapter);
// Start background task
NetworkUtils networkingTask = new NetworkUtils(this);
networkingTask.execute(url);
}
#Override
public void onElementAvailable(ArrayList<Element> elements) {
Log.i(TAG, "elements = " + elements.size());
this.mElementList = new ArrayList<>();
mElementList.clear();
mElementList.addAll(elements);
mElementAdapter.notifyDataSetChanged();
Log.i(TAG, "new elements = " + mElementList.size());
}
#Override
public void onElementClick(View view, int itemIndex) {
Log.v(TAG, "clicked on " + view.getClass().getSimpleName());
int viewId = view.getId();
Context context = this;
String toastMessage = "";
// if (viewId == R.id.product_imageview) {
// toastMessage = "clicked on image of drink item";
// } else if (viewId == R.id.product_item_name || viewId == R.id.product_item_description) {
// toastMessage = "clicked on name or description of drink item";
// } else if (viewId == R.id.product_list_item) {
// toastMessage = "clicked on drink list-item nr: " + itemIndex;
// }
Toast.makeText(context, toastMessage, Toast.LENGTH_LONG)
.show();
}
#Override
public void onClick(View v) {
}
}
Error
D/NetworkUtils: onPreExecute:
D/NetworkUtils: doInBackground was called
D/HostConnection: HostConnection::get() New Host Connection established 0xd4a13c30, tid 27630
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sierendeelementeninbreda, PID: 27595
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at com.example.sierendeelementeninbreda.ElementAdapter.getItemCount(ElementAdapter.java:64)
at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:4044)
at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3849)
at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4404)
at android.view.View.layout(View.java:21912)
at android.view.ViewGroup.layout(ViewGroup.java:6260)
That is the error I get when I run the app, I have tried solving this by looking things up but it is not working. The NullPointerException happens in line 64 of my adapter class. The app basically uses an API to get data from a site and then showcases it in a recylerView.
your not init mElementList before passed to adapter so when adapter call size method
will throw null pointer
edit your code here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
elementRecyclerView= findViewById(R.id.recyclerView_element_list);
elementRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// init mElementList here
mElementList = new ArrayList<>();
mElementAdapter = new ElementAdapter(mElementList,this);
elementRecyclerView.setAdapter(mElementAdapter);
// Start background task
NetworkUtils networkingTask = new NetworkUtils(this);
networkingTask.execute(url);
}
It is always better to do null check
#Override
public int getItemCount() {
if(mElements!=null)
return mElements.size();
else return 0
}
and initialize mElements in constructor
I am trying to use the ProductHunt API to display a list of new posts in a ListView and further expand the list item on click.
On opening the app, the Progress bar appears but after that the app screen stays blank. I think there might be some error in my OnPostExecute method, because when I added a textview to display a string, its getting displayed but my listView is not getting displayed.
I used the standard Apache HttpClient for handling api requests.
I have 4 classes,
MainActivity.java
package com.emoji.apisoup;
/**
* Created by mdhalim on 16/05/16.
*/
import java.io.IOException;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.protocol.HTTP;
public class MainActivity extends Activity {
private ListView lvPosts;
private ProductHuntAdapter adapterPosts;
public static final String POST_DETAIL_KEY = "posts";
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.phunt_main);
String serverURL = "https://api.producthunt.com/v1/posts/";
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
lvPosts = (ListView) findViewById(R.id.lvPosts);
lvPosts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
{
Intent i = new Intent(MainActivity.this, ProductHuntDetail.class);
i.putExtra(POST_DETAIL_KEY, adapterPosts.getItem(position));
startActivity(i);
}
}
});
new LongOperation().execute(serverURL);
}
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Content = new DefaultHttpClient();
private String Error = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(String... urls){
JSONArray items = null;
try {
HttpGet httpget = new HttpGet(urls[0]);
httpget.setHeader("Accept","application/json");
httpget.setHeader("Content-Type","application/json");
httpget.setHeader("Authorization","Bearer 2587aa878d7334e3c89794a6b73ebffb59a06c23b82cd0f789d2ab72d2417739");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String jsonStr = Content.execute(httpget, responseHandler);
Log.d("Response: ", "> " + jsonStr);
JSONObject jsonObj = new JSONObject(jsonStr);
items = jsonObj.getJSONArray("posts");
// Parse json array into array of model objects
ArrayList<ProductHuntList> posts = ProductHuntList.fromJson(items);
// Load model objects into the adapter
for (ProductHuntList post : posts) {
adapterPosts.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
lvPosts.setAdapter(adapterPosts);
}
}
}
ProductHuntList.java containing the JSON Data model and deserializer and a static method for parsing an array of JSON
package com.emoji.apisoup;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.io.Serializable;
/**
* Created by mdhalim on 18/05/16.
*/
public class ProductHuntList implements Serializable {
private static final long serialVersionUID = -8959832007991513854L;
private String name;
private String tagline;
private String screenshot_url;
private String largePosterUrl;
private String discussion_Url;
private String created_at;
private int votes_count;
public String getNames() {
return name;
}
public String getCreated_at() {
return created_at;
}
public String getScreenshot_url() {
return screenshot_url;
}
public String getDiscussion_Url() {
return discussion_Url;
}
public int getVotes_count() {
return votes_count;
}
public String getLargePosterUrl() {
return largePosterUrl;
}
public String getTagline(){
return tagline;
}
public static ProductHuntList fromJson(JSONObject jsonObject) {
ProductHuntList b = new ProductHuntList();
try {
// Deserialize json into object fields
b.name = jsonObject.getString("name");
b.created_at = jsonObject.getString("created_at");
b.tagline = jsonObject.getString("tagline");
b.screenshot_url = jsonObject.getJSONObject("screenshot_url").getString("300px");
b.largePosterUrl = jsonObject.getJSONObject("screenshot_url").getString("850px");
b.votes_count = jsonObject.getInt("votes_count");
b.discussion_Url = jsonObject.getString("discussion_url");
} catch (JSONException e) {
e.printStackTrace();
return null;
}
// Return new object
return b;
}
public static ArrayList<ProductHuntList> fromJson(JSONArray jsonArray) {
ArrayList<ProductHuntList> posts = new ArrayList<ProductHuntList>(jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject productJson = null;
try {
productJson = jsonArray.getJSONObject(i);
} catch (Exception e) {
e.printStackTrace();
continue;
}
ProductHuntList post = ProductHuntList.fromJson(productJson);
if (post != null)
{
posts.add(post);
}
}
return posts;
}
}
ProductHuntAdapter.java this implements the ArrayAdapter
package com.emoji.apisoup;
/**
* Created by mdhalim on 18/05/16.
*/
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by mdhalim on 18/05/16.
*/
public class ProductHuntAdapter extends ArrayAdapter<ProductHuntList> {
public ProductHuntAdapter(Context context, ArrayList<ProductHuntList> aPosts) {
super(context, 0, aPosts);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
ProductHuntList posts = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_product_hunt, null);
}
// Lookup view for data population
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView created = (TextView) convertView.findViewById(R.id.created);
TextView tagline = (TextView) convertView.findViewById(R.id.tagline);
ImageView ivPosterImage = (ImageView) convertView.findViewById(R.id.ivPosterImage);
// Populate the data into the template view using the data object
name.setText(posts.getNames());
created.setText("Created On: " + posts.getCreated_at() + "%");
tagline.setText(posts.getTagline());
Picasso.with(getContext()).load(posts.getScreenshot_url()).into(ivPosterImage);
// Return the completed view to render on screen
return convertView;
}
}
and finally, a class implementing the activity for Item Details when a user clicks on any item on the list.
ProductHuntDetail
package com.emoji.apisoup;
/**
* Created by mdhalim on 18/05/16.
*/
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class ProductHuntDetail extends Activity {
private ImageView ivPosterImage;
private TextView name;
private TextView discusUrl;
private TextView upvotes;
private TextView tagline;
private TextView created;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_hunt_detail);
// Fetch views
ivPosterImage = (ImageView) findViewById(R.id.ivPosterImage);
name = (TextView) findViewById(R.id.name);
discusUrl = (TextView) findViewById(R.id.discusUrl);
created = (TextView) findViewById(R.id.created);
upvotes = (TextView) findViewById(R.id.upvotes);
tagline = (TextView) findViewById(R.id.tagline);
// Load movie data
ProductHuntList posts = (ProductHuntList) getIntent().getSerializableExtra(MainActivity.POST_DETAIL_KEY);
loadMovie(posts);
}
// Populate the data for the movie
#SuppressLint("NewApi")
public void loadMovie(ProductHuntList posts) {
// Populate data
name.setText(posts.getNames());
upvotes.setText(Html.fromHtml("<b>Upvotes:</b> " + posts.getVotes_count() + "%"));
created.setText(posts.getCreated_at());
tagline.setText(posts.getTagline());
discusUrl.setText(Html.fromHtml("<b>Discussion Url:</b> " + posts.getDiscussion_Url()));
// R.drawable.large_movie_poster from
// http://content8.flixster.com/movie/11/15/86/11158674_pro.jpg -->
Picasso.with(this).load(posts.getLargePosterUrl()).
placeholder(R.drawable.large_movie_poster).
into(ivPosterImage);
}
}
I have been trying to debug this for hours :/
Your Async task is returning a void.
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
lvPosts.setAdapter(adapterPosts);
}
As far as I can tell from the code, aPosts is empty.
I think your Async task should be -
AsyncTask<String, Void, ProductHuntAdapter>
and remove -
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
You are creating and updating this in your doInBackground() method already.
I got it!
I didnt need to declare these lines again in my onPostExecute() method
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
So bascially, my new onPostExecute() method goes like this
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
lvPosts.setAdapter(adapterPosts);
}
I had been trying to find this error for last 2 hours, it was harder since, I wasn't even getting any errors. As soon as I posted it on StackOverFlow, seems like I had a divine intervention.
I have would like to rewrite my method so that it returns a List of Movie class rather than a list of String class, here's the method I want to change:
private List<String> getMovieDataFromJson(String forecastJsonStr)
throws JSONException {
JSONObject movieJson = new JSONObject(forecastJsonStr);
JSONArray movieArray = movieJson.getJSONArray("results");
List<String> urls = new ArrayList<>();
for (int i = 0; i < movieArray.length(); i++) {
JSONObject movie = movieArray.getJSONObject(i);
urls.add("http://image.tmdb.org/t/p/w185" + movie.getString("poster_path"));
}
return urls;
}
I tried to rewrite it like this:
private List<Movie> getMovieDataFromJson(String forecastJsonStr)
throws JSONException {
JSONObject movieJson = new JSONObject(forecastJsonStr);
JSONArray movieArray = movieJson.getJSONArray("results");
List<Movie> movies = new ArrayList<>();
for (int i = 0; i < movieArray.length(); i++) {
JSONObject movie = movieArray.getJSONObject(i);
Movie movie1 = new Movie(movie.getString("original_title"), movie.getDouble("vote_average"), movie.getString("release_date"), movie.getString("overview"), movie.getString("poster_path"));
movies.add(movie1);
}
return movies;
}
But the problem is I'm getting error on line 139, it's saying required is String but found Movie instead. Here is line 139:
return getMovieDataFromJson(movieJsonStr);
Here is my code:
package com.projmobileapp.pmdbadd.pmdb;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
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.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
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.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainActivityFragment extends Fragment {
//ArrayAdapter<String> mMovieAdapter;
//String[] movieId,movieTitle,movieOverview,movieReleaseDate,movieVoteAverage;
String[] moviePosterPath = new String[0];
public MainActivityFragment() {
}
MovieAdapter mMovieAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mMovieAdapter = new MovieAdapter(getActivity());
GridView listView = (GridView) rootView.findViewById(R.id.gridview_movie);
listView.setAdapter(mMovieAdapter);
updateMovie();
return rootView;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.mainactivityfragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
updateMovie();
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateMovie() {
FetchMovieTask movieTask = new FetchMovieTask();
movieTask.execute();
}
class FetchMovieTask extends AsyncTask<Void, Void, List<String>> {
private final String LOG_TAG = FetchMovieTask.class.getSimpleName();
#Override
protected List<String> doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String movieJsonStr = null;
try {
URL url = new URL("http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=INSERTAPIKEY");
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.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
movieJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getMovieDataFromJson(movieJsonStr);
} catch (JSONException j) {
Log.e(LOG_TAG, "JSON Error", j);
}
return null;
}
private List<String> getMovieDataFromJson(String forecastJsonStr)
throws JSONException {
JSONObject movieJson = new JSONObject(forecastJsonStr);
JSONArray movieArray = movieJson.getJSONArray("results");
List<String> urls = new ArrayList<>();
for (int i = 0; i < movieArray.length(); i++) {
JSONObject movie = movieArray.getJSONObject(i);
urls.add("http://image.tmdb.org/t/p/w185" + movie.getString("poster_path"));
}
return urls;
}
#Override
protected void onPostExecute(List<String> strings) {
mMovieAdapter.replace(strings);
}
}
class MovieAdapter extends BaseAdapter {
private final String LOG_TAG = MovieAdapter.class.getSimpleName();
private final Context context;
private final List<String> urls = new ArrayList<String>();
public MovieAdapter(Context context) {
this.context = context;
Collections.addAll(urls, moviePosterPath);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = new ImageView(context);
}
ImageView imageView = (ImageView) convertView;
String url = getItem(position);
Log.e(LOG_TAG, " URL " + url);
Picasso.with(context).load(url).into(imageView);
return convertView;
}
#Override
public int getCount() {
return urls.size();
}
#Override
public String getItem(int position) {
return urls.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void replace(List<String> urls) {
this.urls.clear();
this.urls.addAll(urls);
notifyDataSetChanged();
}
}
}
The problem here is that your AsyncTask defines the result type for doInBackground() as List<String>. You need to change the line:
class FetchMovieTask extends AsyncTask<Void, Void, List<String>>
to
class FetchMovieTask extends AsyncTask<Void, Void, List<Movie>>
and change doInBackground() to return List<Movie>
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();
}
public class MainActivity extends Activity {
GridView gridView;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gridView = (GridView) findViewById(R.id.grid_view);
adapter=new LazyAdapter(this, mStrings);
gridView.setAdapter(adapter);
Button b=(Button)findViewById(R.id.button2);
b.setOnClickListener(listener);
}
#Override
public void onDestroy()
{
adapter.imageLoader.stopThread();
gridView.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener(){
public void onClick(View arg0) {
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
private String[] mStrings={
"http://www.globaltvbc.com/uploadedImages/Global_News/Content/Wallpaper.jpeg",
"http://cdn.windows7themes.net/themes/halo-3-hd-wallpaper.jpg",
};
}
The question is i want to display the item on the gridview and display the item in full screen.I want to include any code to display the gridview item in full screen to be in the same class as MainActivity.I dont want my code to be in a new class.
if you want to load the full screen on the same activity then you should use popup window for displaying the image.
or the best solution is implement onItemClickListener on your main activity and on click get the item by position and pass the image url to next activityfor loading it there.
I am giving you my code edit this according to your need
|main Activity
package com.mypack;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RelativeLayout;
public class GridViewActivity extends Activity implements OnItemClickListener {
List<RowItem4> rowItems;
private GridView gridView;
private Button galleryButton;
private Button shareButton;
private String[] mStringArray;
public static final Integer[] partyid = { 1, 2, 3, 4, 18, 19, 20 };
int i = 1;
private String xml;
String output = "";
/*private static final String NAMESPACE = "";
private static final String URL = "";
private static final String SOAP_ACTION = "";
private static final String METHOD_NAME = "";*/
private int pos;
private ProgressDialog progressDialog;
private int galleryId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_view);
Intent i = getIntent();
pos = i.getIntExtra("position", 0);
galleryId = i.getIntExtra("galleryId", 0);
progressDialog = ProgressDialog.show(GridViewActivity.this, "",
"Loading...");
Thread myThread = new Thread() {
private GridViewAdapter adapter;
public void run() {
getImages();
rowItems = new ArrayList<RowItem4>();
for (int i = 0; i < mStringArray.length; i++) {
RowItem4 item = new RowItem4(mStringArray[i]);
rowItems.add(item);
}
// LoadImageFromURL(""
// + output);
adapter = new GridViewAdapter(GridViewActivity.this, rowItems);
runOnUiThread(new Runnable() {
public void run() {
try {
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(GridViewActivity.this);
progressDialog.dismiss();
} catch (final Exception ex) {
Log.i("---", "Exception in thread");
}
}
});
}
};
myThread.start();
setUpView();
}
private void getImages() {
final String envelope = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" "
+ "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" "
+ "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" "
+ "xmlns:tns=\"urn:registerwsdl\">" + "<SOAP-ENV:Body>"
+ "<tns:register " + "xmlns:tns=\"urn:registerwsdl\">"
+ "<galleryid xsi:type=\"xsd:integer\">" + galleryId
+ "</galleryid>" + "<partyid xsi:type=\"xsd:integer\">"
+ partyid[pos] + "</partyid>" + "</tns:register>" +
// "</SOAP-ENV:Body></SOAP-ENV:Envelope>",Name,Email,Password,Status,Type,Date];
"</SOAP-ENV:Body></SOAP-ENV:Envelope>";
System.out.println("------------" + envelope);
CallWebService(URL, SOAP_ACTION, envelope);
org.w3c.dom.Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
ArrayList<String> myList = new ArrayList<String>();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
NodeList nl1 = doc.getElementsByTagName("response");
for (int j = 0; j < nl1.getLength(); j++) {
NodeList nl = doc.getElementsByTagName("url");
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
myList.add(node.getFirstChild().getNodeValue());
}
}
mStringArray = new String[myList.size()];
mStringArray = myList.toArray(mStringArray);
for (int i = 0; i < mStringArray.length; i++) {
Log.d("string is", (mStringArray[i]));
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
String CallWebService(String url, String soapAction, String envelope) {
final DefaultHttpClient httpClient = new DefaultHttpClient();
// request parameters
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 20000);
HttpConnectionParams.setSoTimeout(params, 25000);
// set parameter
HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);
// POST the envelope
HttpPost httppost = new HttpPost(url);
// add headers
httppost.setHeader("soapaction", soapAction);
httppost.setHeader("Content-Type", "text/xml; charset=utf-8");
String responseString = "";
try {
// the entity holds the request
HttpEntity entity = new StringEntity(envelope);
httppost.setEntity(entity);
// Response handler
ResponseHandler<String> rh = new ResponseHandler<String>() {
// invoked when client receives response
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
// get response entity
HttpEntity entity = response.getEntity();
// read the response as byte array
StringBuffer out = new StringBuffer();
byte[] b = EntityUtils.toByteArray(entity);
// write the response byte array to a string buffer
out.append(new String(b, 0, b.length));
return out.toString();
}
};
responseString = httpClient.execute(httppost, rh);
} catch (Exception e) {
Log.v("exception", e.toString());
}
xml = responseString.toString();
// close the connection
System.out.println("xml file ------" + xml);
httpClient.getConnectionManager().shutdown();
return responseString;
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (i == 2) {
if (galleryButton.getVisibility() == View.VISIBLE) {
galleryButton.setVisibility(View.INVISIBLE);
shareButton.setVisibility(View.INVISIBLE);
} else {
galleryButton.setVisibility(View.VISIBLE);
shareButton.setVisibility(View.VISIBLE);
}
i = 0;
}
i++;
super.dispatchTouchEvent(ev);
return false;
}
/*
* public OnTouchListener touch = new View.OnTouchListener() {
*
* public boolean onTouch(View v, MotionEvent event) {
* //System.out.println("onTouch =============-----------"); if
* (galleryButton.getVisibility() == v.VISIBLE) {
* galleryButton.setVisibility(v.INVISIBLE);
*
* shareButton.setVisibility(v.INVISIBLE);
*
* } else { galleryButton.setVisibility(v.VISIBLE);
*
* shareButton.setVisibility(v.VISIBLE);
*
* } return false; } };
*/
private void setUpView() {
gridView = (GridView) findViewById(R.id.gridView1);
galleryButton = (Button) findViewById(R.id.gallery_button);
shareButton = (Button) findViewById(R.id.share_button);
// relativeLayout1.setOnTouchListener(touch);
}
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
Intent i = new Intent(getApplicationContext(), ShowImageActivity.class);
i.putExtra("image", mStringArray[position]);
i.putExtra("galleryId", galleryId);
startActivity(i);
}
}
RowItem4 Object Class
package com.mypack;
public class RowItem4 {
private String imageId;
public String getImageId() {
return imageId;
}
public void setImageId(String imageId) {
this.imageId = imageId;
}
public RowItem4(String mStringArray) {
this.imageId = mStringArray;
}
}
GridViewAdapter extending BaseAdapter
package com.mypack;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
public class GridViewAdapter extends BaseAdapter {
Context context;
List<RowItem4> rowItems;
private ViewHolder holder;
private Drawable d;
public GridViewAdapter(Context context, List<RowItem4> rowItems) {
super();
this.context = context;
this.rowItems = rowItems;
}
private class ViewHolder {
ImageView imageView;
public int position;
}
public int getCount() {
// TODO Auto-generated method stub
return rowItems.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return rowItems.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return rowItems.indexOf(getItem(position));
}
public View getView(int position, View convertView, ViewGroup parent) {
holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.grid_image_view, null);
holder = new ViewHolder();
holder.imageView = (ImageView) convertView.findViewById(R.id.grid_item_image);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
RowItem4 rowItem = (RowItem4) getItem(position);
holder.position = position;
GetXMLTask task = new GetXMLTask(position,holder);
task.execute(new String[] { ""+rowItem.getImageId() });
//holder.imageView.setImageDrawable(d);
return convertView;
}
/*private Drawable LoadImageFromURL(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
d = Drawable.createFromStream(is, "src");
return d;
}catch (Exception e) {
System.out.println(e);
return null;
}
}*/
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
private int mPosition;
private ViewHolder mHolder;
public GetXMLTask(int position, ViewHolder holder) {
mPosition = position;
mHolder = holder;
}
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
protected void onPostExecute(Bitmap result) {
if (mHolder.position == mPosition)
{
mHolder.imageView.setImageBitmap(result);
}
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.
decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
}
This code is if you want to load the image on second activity,and if you want to load image on the same activity just add the code for adding popup window in the main activity. I think now it is clear