NullPointerException in adapter holding viewholders - java

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

Related

Android Can't change imageview [duplicate]

This question already has answers here:
CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch views
(6 answers)
Closed 5 years ago.
I have code that gets an image by its name from drawables, but for some reason it can't update it.
package com.infonuascape.osrshelper.fragments;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.toolbox.ImageLoader;
import com.infonuascape.osrshelper.R;
import com.infonuascape.osrshelper.activities.MainActivity;
import com.infonuascape.osrshelper.models.Account;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
public class BankViewFragment extends OSRSFragment {
private static final String TAG = "BankViewFragment";
private static Account account;
private ListView lv;
private ImageView iv;
Handler handler;
ArrayList<HashMap<String, String>> ItemList;
public static BankViewFragment newInstance(final Account account) {
BankViewFragment fragment = new BankViewFragment();
Bundle b = new Bundle();
fragment.setArguments(b);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.bank_view, null);
ItemList = new ArrayList<>();
new GetItems().execute();
lv = (ListView) view.findViewById(R.id.list);
handler = new Handler(Looper.getMainLooper());
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String nikas = sharedPref.getString("bankname", "null");
return view;
}
public static int getResId(String resourceName, Class<?> c) {
try {
Field idField = c.getDeclaredField(resourceName);
return idField.getInt(idField);
} catch (Exception e) {
throw new RuntimeException("No resource ID found for: "
+ resourceName + " / " + c, e);
}
}
private class GetItems extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
SharedPreferences sharedpreferences = getContext().getSharedPreferences("minescape", Context.MODE_PRIVATE);
String nikas = sharedpreferences.getString("bankname", "null");
String url = "https://api.minesca.pe/game/classic/stats?username=" + nikas;
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "NIKAS: " + nikas);
Log.e(TAG, "ACCOUNT: " + account);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject items = jsonObj.getJSONObject("bank");
Iterator keys = items.keys();
while(keys.hasNext()) {
String dynamicKey = (String)keys.next();
JSONObject line = items.getJSONObject(dynamicKey);
String item = line.getString("item");
//Integer image = getResId(item, Drawable.class);
final Integer image = getResources().getIdentifier(item, "drawable", getActivity().getPackageName());
String amount = line.getString("amount");
Log.e(TAG, "DAIKTAS: " + item);
Log.e(TAG, "KIEKIS: " + amount);
HashMap<String, String> contact = new HashMap<>();
String itembank = item.replaceAll("i_", "");
String itembanks = itembank.replaceAll("_", " ");
contact.put("name", itembanks);
contact.put("email", amount);
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.bank_view, null);
lv = (ListView) view.findViewById(R.id.list);
// iv = (ImageView) view.findViewById(R.id.logo);
final ImageView ims = (ImageView) lv.findViewById(R.id.logo);
handler.post(new Runnable() {
public void run() {
if(image != null) {
Log.e(TAG, "kas cia jam netinka?: " + image);
if(image == 0) {
ims.setImageResource(R.drawable.i_noted);
Log.e(TAG, "kas cia jam netinka?: " + image);
} else {
Log.e(TAG, "kas cia jam netinka?: " + image);
ims.setImageResource(image);
}
} else {
Log.e(TAG, "null?: " + image);
}
}
});
ItemList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
};
}
} else {
Log.e(TAG, "Couldn't get json from server.");
new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(),
"Couldn't get json from server!",
Toast.LENGTH_LONG).show();
}
};
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(getContext(), ItemList,
R.layout.list_item, new String[]{ "email","name"},
new int[]{R.id.email, R.id.name});
lv.setAdapter(adapter);
}
}
}
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.infonuascape.osrshelper, PID: 31024
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at com.infonuascape.osrshelper.fragments.BankViewFragment$GetItems$1.run(BankViewFragment.java:128)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
The problem is that there's a lot of items, and most of them have the resources, but some don't and i would like to just skip those who don't have, but the main problem is that the app crashes while trying to see the bank.
You can't change Views in a non UI thread.
So in order to fix your problem just access UI related stuff in the UI thread, e.g. in onPostExecute()
Do not do this : View should not be touched in another thread except UI thread.
#Override
protected void onPostExecute(Void result) {
-->>>>> DONOT DO THIS --->>>>>lv.setAdapter(adapter);
}

why replace words to question mark in send data to server

I try send data to server but when I send Persian words it sends question marks, for example if I send "سلام" it sends "????"
How can I fix this ?
This is my FragmentForm.class :
package com.skyline.jimmy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import com.skyline.jimmy.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
public class FragmentForm extends Fragment {
// An interface to display or dismiss of ProgressBar
public interface OnSendingRequestToServer {
public void DisplayLoding(boolean setVisibility);
}
private final String TAG = "FragmentForm";
private OnSendingRequestToServer onRequestToServer;
private Context context;
private EditText etName;
private EditText etComment;
private RatingBar ratingBar;
private ImageButton ibSubmit;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
onRequestToServer = (OnSendingRequestToServer) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnConnectingToServer interface.");
}
context = activity.getApplicationContext();
Log.d(TAG, "Fragment attached to activity.");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_form, container, false);
etName = (EditText) view.findViewById(R.id.etName);
etComment = (EditText) view.findViewById(R.id.etComment);
ratingBar = (RatingBar) view.findViewById(R.id.ratingBar);
ibSubmit = (ImageButton) view.findViewById(R.id.ibSubmit);
//TextView tvcm = (TextView) view.findViewById(R.id.tvComment);
Log.d(TAG, "Fragment created.");
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ibSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String strName = etName.getText().toString().trim();
if(strName.length() <= 0) {
Toast.makeText(context, "نام خود را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
String strComment = etComment.getText().toString().trim();
if(strComment.length() <= 0) {
Toast.makeText(context, "متن جک را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
int rate = (int) ratingBar.getRating();
if(rate <= 0) {
Toast.makeText(context, "امتیاز جکتان را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
String deviceId = getDeviceId();
new SendFormTask(deviceId, strName, rate, strComment).execute();
}
private TextView findViewById(int tvcomment) {
// TODO Auto-generated method stub
return null;
}
});
}
private String getDeviceId() {
return Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
}
/*----------------------------------------------------------------------------
* This method is responsible for creating another thread in parallel with
* main UI thread in order to send a request to server and get data (if any).
* ---------------------------------------------------------------------------*/
public class SendFormTask extends AsyncTask<Void, Void, Boolean> {
String deviceId, name, comment;
int rate;
SendFormTask(String deviceId, String strName, int rate, String strComment) {
this.deviceId = deviceId;
this.name = strName;
this.rate = rate;
this.comment = strComment;
}
#Override
protected void onPreExecute() {
Log.d(TAG, "SendFormTask is about to start....");
onRequestToServer.DisplayLoding(true);
}
#Override
protected Boolean doInBackground(Void... params) {
boolean status = false;
HttpURLConnection urlConnection = null;
try {
//URL url = new URL(LinkManager.getFormAPI(deviceId, name, rate, comment));
//URL url = new URL(LinkManager.getFormAPI(deviceId, name, rate, comment));
String url1 = LinkManager.getFormAPI(deviceId, name, rate, comment) ;
//String stUrl = URLEncoder.encode(url1, "UTF-8");
URL url = new URL(url1);
Log.d(TAG, "Try to open: " + url.toString());
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
Log.d(TAG, "Response code is: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream())
);
if (in != null) {
StringBuilder strBuilder = new StringBuilder();
// Read character by character
int ch = 0;
while ((ch = in.read()) != -1)
strBuilder.append((char) ch);
// get returned message and show it
String response = strBuilder.toString();
Log.d("Server response:", response);
if(response.equalsIgnoreCase("1"))
status = true;
}
in.close();
}
}
catch(MalformedURLException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return status;
}
#Override
protected void onPostExecute(Boolean result) {
Log.d(TAG, "SendFormTask finished its task.");
onRequestToServer.DisplayLoding(false);
if(result)
Toast.makeText(context, "جک شما ارسال شد, منتظر تایید آن باشید", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "جک شما ارسال شد , منتظر تایید آن باشید", Toast.LENGTH_LONG).show();
}
}
}
and my LinkManager.class :
package com.skyline.jimmy;
public class LinkManager {
private final static String API_FORM = "http://jimmy.ir/jimmy/sendjoke.php?p1=###&p2=####&p3=#####&p4=######";
private final static String API_Comment = "http://jimmy.ir/jimmy/index.php?p1=###";
public static String getFormAPI(String deviceId, String name, int rate, String comment) {
String url = API_FORM;
url = url.replaceAll("###", deviceId);
url = url.replaceAll("####", name);
url = url.replaceAll("#####", Integer.toString(rate));
url = url.replaceAll("######", comment);
return url;
}
public static String getCommentAPI(String deviceId) {
String url = API_Comment;
url = url.replaceAll("###", deviceId);
return url;
}
}
See this link for accepted characters in URL. Persian characters are not supported as get parameters in a url. You can use http post for sending the data to the server.
first make sure that you are sending right word (persian ) from android side , maybe your java code not sending text in UTF-8 , then make sure that your server, database , and table collection are utf8_persian_ci
and change this
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
to this:
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream(), "utf-8"),8);

String send to web not support utf 8

I try to send some text to web and this is my codes , but it's not support utf8
For example آرین Show ????
how can I delete this problem?!
This is supported English ...
FragmentForm
package com.kamalan.phpandroidapi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
public class FragmentForm extends Fragment {
// An interface to display or dismiss of ProgressBar
public interface OnSendingRequestToServer {
public void DisplayLoding(boolean setVisibility);
}
private final String TAG = "FragmentForm";
private OnSendingRequestToServer onRequestToServer;
private Context context;
private EditText etName;
private EditText etComment;
private RatingBar ratingBar;
private ImageButton ibSubmit;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
onRequestToServer = (OnSendingRequestToServer) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnConnectingToServer interface.");
}
context = activity.getApplicationContext();
Log.d(TAG, "Fragment attached to activity.");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_form, container, false);
etName = (EditText) view.findViewById(R.id.etName);
etComment = (EditText) view.findViewById(R.id.etComment);
ratingBar = (RatingBar) view.findViewById(R.id.ratingBar);
ibSubmit = (ImageButton) view.findViewById(R.id.ibSubmit);
//TextView tvcm = (TextView) view.findViewById(R.id.tvComment);
Log.d(TAG, "Fragment created.");
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ibSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String strName = etName.getText().toString().trim();
if(strName.length() <= 0) {
Toast.makeText(context, "نام خود را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
String strComment = etComment.getText().toString().trim();
if(strComment.length() <= 0) {
Toast.makeText(context, "متن جک را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
int rate = (int) ratingBar.getRating();
if(rate <= 0) {
Toast.makeText(context, "امتیاز جکتان را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
String deviceId = getDeviceId();
new SendFormTask(deviceId, strName, rate, strComment).execute();
}
private TextView findViewById(int tvcomment) {
// TODO Auto-generated method stub
return null;
}
});
}
private String getDeviceId() {
return Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
}
/*----------------------------------------------------------------------------
* This method is responsible for creating another thread in parallel with
* main UI thread in order to send a request to server and get data (if any).
* ---------------------------------------------------------------------------*/
public class SendFormTask extends AsyncTask<Void, Void, Boolean> {
String deviceId, name, comment;
int rate;
SendFormTask(String deviceId, String strName, int rate, String strComment) {
this.deviceId = deviceId;
this.name = strName;
this.rate = rate;
this.comment = strComment;
}
#Override
protected void onPreExecute() {
Log.d(TAG, "SendFormTask is about to start...");
onRequestToServer.DisplayLoding(true);
}
#Override
protected Boolean doInBackground(Void... params) {
boolean status = false;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(LinkManager.getFormAPI(deviceId, name, rate, comment));
Log.d(TAG, "Try to open: " + url.toString());
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
Log.d(TAG, "Response code is: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
if (in != null) {
StringBuilder strBuilder = new StringBuilder();
// Read character by character
int ch = 0;
while ((ch = in.read()) != -1)
strBuilder.append((char) ch);
// get returned message and show it
String response = strBuilder.toString();
Log.d("Server response:", response);
if(response.equalsIgnoreCase("1"))
status = true;
}
in.close();
}
}
catch(MalformedURLException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return status;
}
#Override
protected void onPostExecute(Boolean result) {
Log.d(TAG, "SendFormTask finished its task.");
onRequestToServer.DisplayLoding(false);
if(result)
Toast.makeText(context, "جک شما ارسال شد, منتظر تایید آن باشید", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "جک شما ارسال شد , منتظر تایید آن باشید", Toast.LENGTH_LONG).show();
}
}
}
and LinkManager.java for link to web
public class LinkManager {
private final static String API_FORM = "http://example.com/sendjoke.php?p1=###&p2=####&p3=#####&p4=######";
private final static String API_Comment = "http://example.com/index.php?p1=###";
public static String getFormAPI(String deviceId, String name, int rate, String comment) {
String url = API_FORM;
url = url.replaceAll("###", deviceId);
url = url.replaceAll("####", name);
url = url.replaceAll("#####", Integer.toString(rate));
url = url.replaceAll("######", comment);
url = url.replaceAll(" ", "%20");
return url;
}
public static String getCommentAPI(String deviceId) {
String url = API_Comment;
url = url.replaceAll("###", deviceId);
return url;
}
}
Please Help me.
Sry My English is bad.
Try to use urlencoding. like :HttpGet get = new HttpGet(URLEncoder.encode(url,"UTF-8"));
url is the specific urllink.And If You want to use httppost, encode the entity before setEntity

ListViewActivity with Custom Adapter doesn' t work

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);

displaying selected grid image in Full Screen and the code for this needs to be in the MainActivity class as shown below

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

Categories

Resources