Using pagination for listview in android - java

I want to use pagination for a listview in android.I am loading 10 values at a time from a web service.But the problem is that the group of 10 values keep repeating.I have used an array list called ice_data for the adapter of the listview.The code:
public class VideoActivity extends Activity {
private ConnectionDetector cd;
public HttpResponse video_respons;
public String video_string_response1;
public ArrayList<NameValuePair> nameValuePairs_Video;
ArrayList<Ice_data> ice_list;
String URL="http://footballultimate.com/icebucket/index.php/api/getVideo";
String URL1="http://footballultimate.com/icebucket/index.php/api/getVideoByLimit";
JSONObject jsonobj;
JSONArray jsonarr;
Ice_data iceobj;
CustomIceAdapter ciadp;
ListView list;
int start = 1;
int limit = 10;
boolean loadingMore = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
ice_list=new ArrayList<Ice_data>();
// GEt all Data for Video
cd = new ConnectionDetector(VideoActivity.this);
Config.isInternetPresent = cd.isConnectingToInternet();
if (!Config.isInternetPresent) {
AlertDialog.Builder builder = new AlertDialog.Builder(VideoActivity.this);
// Shuld be fail icon
builder.setIcon(R.drawable.ic_launcher);
builder.setMessage("Connection Not Available !" + "\n"
+ "Please enable your Internet Connection");
builder.setTitle("INTERNET CONNECTION");
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
new GetVideos().execute();
}
// Get all Data for Video
list= (ListView) findViewById(R.id.videoList);
list.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView arg0, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if((lastInScreen == totalItemCount) && !(loadingMore)){
new GetVideos().execute();
}
}
});
}
class GetVideos extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
private HttpResponse vip_respons;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(VideoActivity.this);
pDialog.setTitle("Processing...");
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
loadingMore = true;
//ice_list=new ArrayList<Ice_data>();
// TODO Auto-generated method stub
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL1);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("start",String.valueOf(start)));
nameValuePairs.add(new BasicNameValuePair("limit",String.valueOf(limit)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
video_respons = httpclient.execute(httppost);
//video_string_response1 = getResponseBody(video_respons);
video_string_response1=responsetostring.getResponseBody(video_respons);
//Log.d("Store_Response", the_string_response1);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String video_string) {
try{
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
catch(Exception e){
e.printStackTrace();
}
finally
{
pDialog.dismiss();
}
if (video_string_response1!=null) {
//displayjsonstring();
geticevalues(video_string_response1);
}
}
}
public void geticevalues(String result)
{
try {
jsonobj=new JSONObject(result);
//ice_list=new ArrayList<Ice_data>();
jsonarr=jsonobj.getJSONArray("video_data");
for(int i=0;i<jsonarr.length();i++)
{
JSONObject jso=jsonarr.getJSONObject(i);
iceobj=new Ice_data();
iceobj.title=jso.getString("title");
iceobj.image_URL=jso.getString("image");
iceobj.video_URL=jso.getString("url");
ice_list.add(iceobj);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ciadp=new CustomIceAdapter(VideoActivity.this,ice_list);
loadingMore = false;
ciadp.notifyDataSetChanged();
list.setAdapter(ciadp);
start+=10;
}
How do i prevent the duplication of the values in the listview.?

Related

FirebaseMessagingService is not getting called in AsyncTask's doInBackground

I have push Notification and I want to update realm objects when the phone gets a notification but when I try launch this:
RealmModelActiveUser actUser= realm.where(RealmModelActiveUser.class).equalTo("id",1).findFirst();
int myid= actUser.getUser().getUser_id();
new ServerBackgroundDownloadConversations(getApplicationContext()) {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (!result.equals("Error")) {
Log.i("Conversation", "UPDATED");
}
}
}.execute(myid);
The program jumps into the constructor ServerBackgroundDownloadConversations(getApplicationContext()) but doesn't call doInBackground and I don't know why.
My AsyncTask:
public class ServerBackgroundCreateConversation extends AsyncTask<RealmModelConversations,Void,String> {
Context context;
Handler handler;
String out= "";
#SuppressLint("HandlerLeak")
public ServerBackgroundCreateConversation(Context context) {
this.context = context;
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Bundle bundle= msg.getData();
if (bundle!=null){
out = (String) bundle.get("response");
} else {
out= "Error";
}
}
};
}
#Override
protected String doInBackground(RealmModelConversations... params) {
RealmModelConversations newConv = params[0];
UploadImageApacheHttp uploadTask = new UploadImageApacheHttp();
uploadTask.doFileUpload(newConv.getWork(newConv.getIntWork()), newConv, handler);
while (out.equals("")){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return out;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String result) {
if (!result.equals("]") || !result.equals("")){
/// prihlási nového user aj do active (login/register)
CreateNewConversation(result);
} else {
result="Error";
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
private void CreateNewConversation(String result){
Realm realm= Realm.getDefaultInstance();
try {
Gson gson = new Gson();
Type typeConv = new TypeToken<JsonSablonaConversations>() {
}.getType();
JSONObject pom;
JSONArray parentArray = new JSONArray(result);
JSONObject finalObject = parentArray.getJSONObject(0);
JsonSablonaConversations conversation = gson.fromJson(finalObject.toString(), typeConv);
final RealmModelConversations NewUserConv = new RealmModelConversations();
NewUserConv.setId_dialog(conversation.getId_dialog());
NewUserConv.setDate(conversation.getDate());
NewUserConv.setKey(conversation.getKey());
NewUserConv.setId_user(conversation.getId_user());
NewUserConv.setId_user2(conversation.getId_user2());
NewUserConv.setMeno(conversation.getMeno());
NewUserConv.setMeno2(conversation.getMeno2());
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
try {
realm.copyToRealmOrUpdate(NewUserConv);
} catch (Exception e) {
int pom=4;
}
RealmResults<RealmModelConversations> ru= realm.where(RealmModelConversations.class).findAll();
}
});
}
catch (Exception e) {
int ppp=4;
ppp++;
}finally {
realm.close();
}
}
}
I try calling this ↑ from an external thread which is called from a Service, but my AsyncTask has handler and handler needs to be in runOnUIthread and in Thread. I can't get Activity because the thread is called from a Service which doesn't have access to Activity.
I solved my problem with this code
public String postData(int myUserId) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.gallopshop.eu/OFY/getConversations.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", Integer.toString(myUserId)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String responseStr = EntityUtils.toString(response.getEntity());
return responseStr;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
I will try to put this method & after this method into simply thread, But maybe it's not needed because it's in a service.
Question - Do I put this into Thread or do you think it'll affect the performance of the app?

Error In MyTask with URLEncoder - android & java

I'm using URLEncoder in my activity. but i have a error in MyTask. I have marked the error with Error in my code.
public class Search_Ringtone extends SherlockActivity{
ListView lsv_latest;
List<ItemRingCategoryItem> arrayOfRingcatItem;
RingCateItemAdapter objAdapterringitemitem;
AlertDialogManager alert = new AlertDialogManager();
private ItemRingCategoryItem objAllBean;
JsonUtils util;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ringcatitem_activity);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
lsv_latest=(ListView)findViewById(R.id.latest_list);
arrayOfRingcatItem=new ArrayList<ItemRingCategoryItem>();
if (JsonUtils.isNetworkAvailable(Search_Ringtone.this)) {
String str = Constant.SEARCH_RINGTONE_URL+Constant.SEARCH.replace(" ", "%20");
String myUrl = URLEncoder.encode(str, "UTF-8");
MyTask().execute(myUrl); //*Error*
} else {
showToast("No Network Connection!!!");
alert.showAlertDialog(Search_Ringtone.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
}
lsv_latest.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
objAllBean=arrayOfRingcatItem.get(position);
Intent intplay=new Intent(getApplicationContext(),SingleRingtone.class);
Constant.RINGTONE_ITEMID=objAllBean.getRingItemId();
startActivity(intplay);
}
});
}
private class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Search_Ringtone.this);
pDialog.setMessage("لطفا صبر کنید...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
if (null == result || result.length() == 0) {
showToast("Server Connection Error");
alert.showAlertDialog(getApplicationContext(), "Server Connection Error",
"May Server Under Maintaines Or Low Network", false);
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.LATEST_ARRAY_NAME);
JSONObject objJson = null;
if(jsonArray.length()==0)
{
showToast("موردی پیدا نشد!");
}
else
{
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemRingCategoryItem objItem = new ItemRingCategoryItem();
objItem.setRingItemId(objJson.getString(Constant.CATEITEMRING_RINDID));
objItem.setRingItemCatId(objJson.getString(Constant.CATEITEMRING_RINDCATID));
objItem.setRingItemCatName(objJson.getString(Constant.CATEITEMRING_CATENAME));
objItem.setRingItemName(objJson.getString(Constant.CATEITEMRING_RINGNAME));
objItem.setRingItemUrl(objJson.getString(Constant.CATEITEMRING_RINDURL));
objItem.setRingItemDownCount(objJson.getString(Constant.CATEITEMRING_RINDDOWNCOUNT));
objItem.setRingItemUser(objJson.getString(Constant.CATEITEMRING_RINDUSER));
objItem.setRingItemTag(objJson.getString(Constant.CATEITEMRING_RINDTAG));
objItem.setRingItemSize(objJson.getString(Constant.CATEITEMRING_RINDSIZE));
objItem.setRingStar(objJson.getString(Constant.LATESTRING_RINGSTAR));
objItem.setRingImage(objJson.getString(Constant.LATESTRING_RINGIMAGE));
arrayOfRingcatItem.add(objItem);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
setAdapterToListview();
}
}
}
Shouldn't it be new MyTask().execute(myURL);?
Also because it's an AsyncTask you need to retain a reference to it until it's finished or else the garbage collector destroys it.
i write like this and solved thank you everyone:
if (JsonUtils.isNetworkAvailable(Search_Ringtone.this)) {
String str = Constant.SEARCH_RINGTONE_URL+Constant.SEARCH.replace(" ", "%20");
String myUrl = null;
try {
myUrl = URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new MyTask().execute(myUrl);

Android Search Listview duplicating items from JSON using EditText

I'm creating a simple search activity using EditText, ListView, JSON and Database, Every time i enter text in EditText, the listview must update(I'm using mysql, Select query LIKE), where the ListView that contains Items from Database using JSON, the items must be updated from the given condition using LIKE method, but it keeps in duplicating item in ListView every time i enter text.
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
name = inputSearch.getText().toString();
searcher(name);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
String result;
private void searcher(String searched){
class searching extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
String paramSearched = params[0];
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://....p.com/searchD.php?name=" + paramSearched);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
InputStream is = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(is);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
result = stringBuilder.toString();
}catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONObject obj = new JSONObject(result);
nameslist = obj.getJSONArray("list");
for(int i = 0; i < nameslist.length(); i++){
JSONObject c = nameslist.getJSONObject(i);
String id = c.getString("ID");
String name = c.getString("Name");
HashMap<String, String> map = new HashMap<String, String>();
map.put("ID", id);
map.put("Name", name);
listofnames.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Search.this);
pDialog.setMessage("Searching Name. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected void onPostExecute(String s) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
Search.this, listofnames,
R.layout.list_item1, new String[]{"ID",
"Name"},
new int[]{R.id.pid, R.id.name});
lv.setAdapter(adapter);
}
});
adapter.notifyDataSetChanged();
}
}
searching sh = new searching();
sh.execute(searched);
}
I think you should clear the "listofnames" list before you add new data into it to keep the list data newest and not duplicated.

Android : getParams() called two times dont know why?

Here getParams() method called two times and added two times data at my server. I have also noticed that my logs print twice in logcat. It occurs when I check two checkbox of from contact picker list view to send data to server.
Here is my json data :
{
"send_data":[{
"gcm_reg_id":
"APA91bFPfAvEL_UJRHiOSohkekTh7M9qj1Kj307kFqmWh4VS8Re1aeejWSKXQnJb7q3OIjykCccbbI-0pn14DwvyjjL4ynQTHNR-m1p3vxLKy7ujGXv2MpIe0fhT2vcTJE0SW0uTjkD9iPJz0pw3sMuGojA4yxw0zg", "receiver_id":
"170"
},{
"gcm_reg_id":
"APA91bFheDJdBe3LwBk7MNchLitnKkECgVARxopr0HnFemo1vfW3Q0Mt1m6GXxccoq-wjUwoV-yXOVvcw9JwXcOZwAPyal9ZqMoA-U3fLNdaMa7pu8f-GYSyMsv16XKkgzPpzOPPKs8pc9C-7K1MhZXKgRf67DiXTSRY67swIOGP1XmJyoa3l1s", "receiver_id":
"166"
}]
}
Here is my code :
public class ContacsPicker extends ListActivity implements OnClickListener{
ProgressDialog dialog;
ConnectionDetector cd;
String phoneNumber ;
String conatct_num;
ArrayList<integer> status;
ImageView iv;
ArrayList<PhoneContactInfo> list;
JSONArray contact_noArray;
ArrayList<String> contact_database;
ArrayList<String> contact_userid;
ArrayList<String> image;
ListView list_view;
CustomListViewAdapter adpter;
String user_id,message,level,time,image_name,receiver_id,regId,mail;
Bitmap send_image;
Store_pref obj_Store_pref;
RegisterUser obj_RegisterUser;
ProgressDialog Dialog;
EditText edt_search;
ImageView iv_search;
RelativeLayout relative_search;
Boolean is_serch=false;
Matrix matrix = new Matrix();
send_data obj_Send_data;
String sender_regid,ba1, data;
Context mContext;
public Uri targetUri;
JSONObject obj;
Button button1_send;
ArrayList<String> checkedValue;
ArrayList<send_data> id_arrArrayList;
List<com.waycreon.picture_puzzle.model.RegisterUser.Registure_user> Registure_user;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts_picker);
mContext=this;
edt_search =(EditText) findViewById(R.id.edt_search);
iv_search=(ImageView)findViewById(R.id.iv_search);
button1_send=(Button) findViewById(R.id.button1_send);
button1_send.setOnClickListener(this);
relative_search=(RelativeLayout)findViewById(R.id.relative_search);
set_invisible_relative_search();
obj_Store_pref=new Store_pref(ContacsPicker.this);
regId=obj_Store_pref.get_GCMreg_id();
mail=obj_Store_pref.get_mail_id();
Log.i("GCM reg id in contact picker class", "++++"+regId);
Log.i("mail id in contact picker class", "++++"+mail);
iv_search.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(!is_serch)
{
is_serch=true;
search_click();
}
else
{
is_serch=false;
close_click();
}
}
});
list_view=getListView();
message = getIntent().getStringExtra("message");
level = getIntent().getStringExtra("level");
time = getIntent().getStringExtra("time");
targetUri= (Uri) getIntent().getParcelableExtra("targetUri");
Log.i("get message", message);
Log.i("get level", level);
Log.i("get time", time);
Log.i("get send_image", send_image+"=");
Log.i("target uri", ""+targetUri);
try {
int orientation = getOrientation(this, targetUri);
Log.i("orientation on create", "++"+orientation);
matrix.postRotate(orientation);
send_image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), targetUri);
send_image= get_Resized_Bitmap(send_image,600,800);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
send_image.compress(Bitmap.CompressFormat.JPEG, 100, bao);
byte [] ba = bao.toByteArray();
ba1=Base64.encodeToString(ba,1);
Log.i("base 64", ba1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
status=new ArrayList<integer>();
contact_database=new ArrayList<String>();
contact_userid=new ArrayList<String>();
image=new ArrayList<String>();
cd=new ConnectionDetector(this);
obj_Store_pref= new Store_pref(this);
dialog = new ProgressDialog(ContacsPicker.this);
dialog.setCancelable(false);
dialog.setMessage("Please Wait...");
dialog.setCancelable(false);
list = getAllPhoneContacts();
get_registered_no();
edt_search = (EditText) findViewById(R.id.edt_search);
edt_search .addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = edt_search .getText().toString()
.toLowerCase(Locale.getDefault());
adpter.filter(text);
list_view.setAdapter(adpter);
adpter.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
});
id_arrArrayList=new ArrayList<send_data>();
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
CheckBox cb = (CheckBox) arg1.findViewById(R.id.checkBox1_check);
cb.performClick();
receiver_id =arg1.getTag().toString();
// String gcm_reg_id=Registure_user.get(arg2).gcm_regid;
// Log.i("gcm_reg id on list click", gcm_reg_id);
Log.i("in if", receiver_id+"++++");
if(!arg1.getTag().equals("0"))
{
String[] separated = arg1.getTag().toString().split(" ");
String receiver_id =separated[0];
String gcm_reg_id=separated[1];
if (cb.isChecked()) {
Log.i("in if check box", receiver_id+"++++");
obj_Send_data = new send_data();
obj_Send_data.setReceiver_id(receiver_id);
obj_Send_data.setGcm_reg_id(gcm_reg_id);
id_arrArrayList.add(obj_Send_data);
Log.i("arraylist in if lisze", "++"+ id_arrArrayList.size());
} else if (!cb.isChecked()) {
id_arrArrayList.remove(obj_Send_data);
Log.i("arraylist in else lisze", "++"+ id_arrArrayList.size());
}
}
// if(!arg1.getTag().equals("0"))
// {
// receiver_id =arg1.getTag().toString();
// show_alert_invitation("Invitation","Are you sure you want to send puzzle to your friend ?");
//
// Log.i("in if ", receiver_id+"++++");
//
// Get_receiver_reg_id();
//
//
// }
// else
// {
// show_alert_unregister_user("Notification",getString(R.string.unregister_user_message));
// }
}
});![enter image description here][1]
}
public void onClick(View v) {
if(v==button1_send)
{
// Log.i("array list", receiver_id);
// Send_data();
show_alert_invitation("Invitation","Are you sure you want to send task to your friend ?");
}
}
private void get_registered_no() {
// TODO Auto-generated method stub
if (cd.isConnectingToInternet())
{
dialog.show();
RequestQueue queue = Volley.newRequestQueue(ContacsPicker.this);
String url="http://karmamobichamps.com/Restaurant_app/puzzle/puzzle_app_services.php?do=get_registered_no";
Log.i("url", url+"+++++++++++");
StringRequest myReq = new StringRequest(Method.GET,url,
Get_Event_list_ReqSuccessListener(),
Get_Event_list_ReqErrorListener());
queue.add(myReq);
}
else
{
cd.show_alert("no connection", "Please check with your internet Connection");
}
}
private ErrorListener Get_Event_list_ReqErrorListener() {
return new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Log.i("Volly err", error.getLocalizedMessage()+"++++");
error.printStackTrace();
}
};
}
private Listener<String> Get_Event_list_ReqSuccessListener() {
return new Response.Listener<String>() {
public void onResponse(String response) {
dialog.dismiss();
Log.i("registration data", response+"");
try {
JSONObject jo=new JSONObject(response);
if(jo.getString("ResponseCode").equals("1"))
{
try
{
Gson gson = new GsonBuilder().create();
obj_RegisterUser= gson.fromJson(response, RegisterUser.class);
Registure_user=obj_RegisterUser.Registure_user;
Log.i("user size", Registure_user.size()+"--");
}
catch (Exception e) {
e.printStackTrace();
}
}
} catch (JSONException e1) {
e1.printStackTrace();
}
for(int i=0;i<list.size();i++)
{
image.add("0");
}
for(int i=0;i<list.size();i++)
{
for(int j=0;j<Registure_user.size();j++)
{
String[] separated = Registure_user.get(j).mobile_no.split(" ");
String mobilenono = separated[separated.length-1];
String country_code = separated[0];
// String mobilenono=separated[1];
String mobile_no=country_code+mobilenono;
if(list.get(i).getcontactNumber().equals(mobilenono) || list.get(i).getcontactNumber().equals(mobile_no) ||(list.get(i).getcontactNumber().equals(Registure_user.get(j).mobile_no)) ||list.get(i).getcontactNumber().equals("0"+mobilenono)) {
image.set(i,Registure_user.get(j).id.toString()+" "+Registure_user.get(j).gcm_regid.toString());
Log.i("match", list.get(i).getcontactNumber()+"==");
}
}
}
adpter=new CustomListViewAdapter(ContacsPicker.this, list,Registure_user,image);
list_view.setAdapter(adpter);
}
};
}
private void Send_data() {
data=Write_json();
Log.i("in send data method", data);
Dialog=new ProgressDialog(this);
Dialog.setTitle("sending..");
Dialog.setCancelable(false);
Dialog.show();
RequestQueue queue = Volley.newRequestQueue(ContacsPicker.this);
String url = null;
url = "http://karmamobichamps.com/Restaurant_app/puzzle/send_multi_data.php" ;
StringRequest myReq = new StringRequest(Method.POST,url,
send_data_ReqSuccessListener(),
send_data_ReqErrorListener())
{
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
// HashMap<String, String> params = new HashMap<String, String>();
// {
**params.put("data", data);
params.put("image", ba1);
params.put("sender_id", obj_Store_pref.get_user_id());
params.put("message", message);
params.put("level",level);
params.put("time", time);
params.put("status", "1");
Log.i("data in params", data);
Log.i("sender_id in params", obj_Store_pref.get_user_id());
Log.i("level",level);
Log.i("message in params", message);
Log.i("time in params", time);
Log.i("status in params", "1");**
return params;
};
};
queue.add(myReq);
}
private ErrorListener send_data_ReqErrorListener() {
return new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Dialog.dismiss();
Log.i("Volly err", error.getLocalizedMessage()+"++++");
error.printStackTrace();
}
};
}
private Listener<String> send_data_ReqSuccessListener() {
return new Response.Listener<String>() {
public void onResponse(String response) {
Dialog.dismiss();
Log.i("registration data", response+"");
try {
JSONObject jo=new JSONObject(response);
if (jo.getString("ResponseCode").equals("1")) {
finish();
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
}
private void send_to_web() {
// TODO Auto-generated method stub
final String URL = "http://karmamobichamps.com/Restaurant_app/puzzle/send_multi_data.php";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("data", data);
// params.put("image", ba1);
// params.put("sender_id", obj_Store_pref.get_user_id());
// params.put("message", message);
// params.put("level",level);
// params.put("time", time);
// params.put("status", "1");
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
ApplicationController.getInstance().addToRequestQueue(req);
}
private void show_alert_invitation(String title,String msg) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(title)
.setMessage(msg)
.setCancelable(false)
.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// new ImageUpload().execute();
Send_data();
// send_to_web();
Log.i("bitmap width in contact picker", ""+send_image.getWidth());
Log.i("bitmap height in contact picker", ""+send_image.getHeight());
dialog.cancel();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private void show_alert_unregister_user(String title,String msg) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(title)
.setMessage(msg)
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "Swapatask");
String sAux = "\nHeyy use this amazing application i m using too...\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=com.waycreon.picture_puzzle \n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "choose one"));
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
private void set_visible_relative_search() {
relative_search.setVisibility(RelativeLayout.VISIBLE);
}
private void set_invisible_relative_search() {
relative_search.setVisibility(RelativeLayout.GONE);
}
private void search_click() {
iv_search.setImageResource(R.drawable.close);
set_visible_relative_search();
edt_search.setFocusable(true);
}
private void close_click() {
iv_search.setImageResource(R.drawable.search_button);
set_invisible_relative_search();
edt_search.setText("");
}
/*============================get local to phone all contect===================================*/
public ArrayList<PhoneContactInfo> getAllPhoneContacts() {
Log.d("START","Getting all Contacts");
ArrayList<PhoneContactInfo> arrContacts = new ArrayList<PhoneContactInfo>();
PhoneContactInfo phoneContactInfo=null;
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
Cursor cursor = getContentResolver().query(uri, new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone._ID}, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
cursor.moveToFirst();
while (cursor.isAfterLast() == false)
{
String contactNumber= cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
int phoneContactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
if (contactNumber.length()>0)
{
phoneContactInfo = new PhoneContactInfo();
phoneContactInfo.setphoneContactID(phoneContactID);
phoneContactInfo.setcontactName(contactName);
phoneContactInfo.setcontactNumber(contactNumber.replaceAll("\\s+",""));
arrContacts.add(phoneContactInfo);
}
phoneContactInfo = null;
cursor.moveToNext();
}
cursor.close();
cursor = null;
Log.d("END","Got all Contacts");
return arrContacts;
}
private void Send_push() {
// Dialog.show();
RequestQueue queue = Volley.newRequestQueue(ContacsPicker.this);
String url = null;
try {
url = "http://karmamobichamps.com/Restaurant_app/puzzle/puzzle_app_services.php?do=Receive_Push_notification&gcm_regid="
+sender_regid+"&message="+URLEncoder.encode("You Have Received Swapatask Request", "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("rgister url", url);
StringRequest myReq = new StringRequest(Method.GET,url,
Registration_ReqSuccessListener(),
Registration_ReqErrorListener());
queue.add(myReq);
}
private ErrorListener Registration_ReqErrorListener() {
return new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
// Dialog.dismiss();
Log.i("Volly err", error.getLocalizedMessage()+"++++");
error.printStackTrace();
}
};
}
private Listener<String> Registration_ReqSuccessListener() {
return new Response.Listener<String>() {
public void onResponse(String response) {
// Dialog.dismiss();
Log.i("registration data", response+"");
//
}
};
}
public Bitmap get_Resized_Bitmap(Bitmap bmp, int newHeight, int newWidth) {
int width = bmp.getWidth();
int height = bmp.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
// Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// matrix.postRotate(90);
// "RECREATE" THE NEW BITMAP
Bitmap newBitmap = Bitmap.createBitmap(bmp, 0, 0, width, height, matrix, true);
return newBitmap ;
}
public static int getOrientation(Context context, Uri photoUri) {
/* it's on the external media. */
Cursor cursor = context.getContentResolver().query(photoUri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
if (cursor.getCount() != 1) {
return -1;
}
cursor.moveToFirst();
return cursor.getInt(0);
}
private String Write_json() {
// TODO Auto-generated method stub
Log.i("arraylist lisze in next button", "++"+ id_arrArrayList.size());
obj = new JSONObject();
JSONArray list1 = new JSONArray();
try {
for (int i = 0; i < id_arrArrayList.size(); i++) {
String gcm_reg_id=Registure_user.get(i).gcm_regid;
JSONObject jsonObject=new JSONObject();
jsonObject.put("receiver_id", id_arrArrayList.get(i).getReceiver_id());
jsonObject.put("gcm_reg_id", id_arrArrayList.get(i).getGcm_reg_id());
Log.i("gcm_reg_id", gcm_reg_id);
list1.put(jsonObject);
}
obj.put("send_data", list1);
}catch (Exception e) {
e.printStackTrace();
}
return obj.toString();
}
// public class ImageUpload extends AsyncTask<String, String,String>
// {
// Bitmap bitmap;
// public ImageUpload()
// {
// // TODO Auto-generated constructor stub
//// this.bitmap=bitmap;
// }
// #Override
// protected void onPreExecute()
// {
// dialog.show();
// super.onPreExecute();
//
// }
// #Override
// protected String doInBackground(String... params)
// {
// // TODO Auto-generated method stub
// try
// {
//// ByteArrayOutputStream bao = new ByteArrayOutputStream();
//// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bao);
//// byte [] ba = bao.toByteArray();
//// String ba1=Base64.encodeToString(ba,1);
// Log.i("base 64", ba1);
// ArrayList<NameValuePair> nameValuePairs = new enter code hereArrayList<NameValuePair>();
// HttpClient httpclient = new DefaultHttpClient();
// HttpPost httppost = new HttpPost("http://karmamobichamps.com/Restaurant_app/puzzle/send_multi_data.php");
// Log.i("url", ""+httppost);
// nameValuePairs.add(new BasicNameValuePair("data", data));
// nameValuePairs.add(new BasicNameValuePair("image", ba1));
// nameValuePairs.add(new BasicNameValuePair("sende
To identify the root of this issue you'll need to debug and see what's the path in which getParams is called.
You could either breakpoint within getParams block or print the stack trace to log like so:
Throwable throwable = new IllegalArgumentException("Something");
throwable.printStackTrace();
Add this before adding request to request queue
request.setRetryPolicy(new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

How to integrate with jsonwebservices in Android?

I'm implementing json_web services in my Android application. I want to send the json data on jsonwebservices which is created in Java. When I run the application data does not send from the Android and does not show any error and also does not show any type of exception.
How can I identify whether my data is sent or not?
Here is my Activity Code:
public class Login extends Activity
{
Button btnLogin;
EditText etextUsername , etextPassword;
String strUserName , strPassWord ;
ProgressDialog pDialog;
JSONObject jObject ;
SharedPreferences.Editor editor;
SharedPreferences sharedPref1;
String str_Device_IP_Address=null;
JSONArray user = null;
String pref_filename = "IP_ADDRESS";
static final String KEY_REQUEST_ID = "RequestId";
static final String KEY_REQUEST_CODE = "RequestCode";
static final String KEY_CHANNEL_ID = "ChannelId";
static final String KEY_IP_ADDRESS="IPAddress";
static final String KEY_USERNAME="UserId";
static final String KEY_PASSWORD="Password";
static final String KEY_REQUEST="Request";
static final String KEY_VENDOR_ID="VendorId";
String RequestId="77777";
String RequestCode="001";
String stringChannelId="MobileApp";
String strIpAddress = null;
private String textToEncrypt = "Hi, this is a test to check its gone work or not.";
String encrypted = "MzA3RDBCMjMxMjQzNzcxREUxMUYxNjg1NzgwOTU1MjU1M0FDOUZEN0M3Q0JGQ0Q5MTI2NEIyNTE2"
+ "OTQwQTc3NjM2QTBCRDFDMUEyNkUwRjlDMzQwN0U0MEI0NDg2M0JBMDU1OThCNTI1NTZCMEFGNjk1NjJFNzZBMUE0NzM4NTQ=";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final Context context = getApplicationContext();
connectWithHttpGet_IpAddress();
etextUsername = (EditText)findViewById(R.id.edittext_username);
etextPassword = (EditText)findViewById(R.id.edittext_password);
btnLogin=(Button)findViewById(R.id.button_Login);
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if (!isOnline())
{
showNoConnectionDialog(Login.this);
}
else
{
connectWithHttpGet_LoginData();
}
}
});
}
private void connectWithHttpGet_LoginData()
{
class GetJSONParse extends AsyncTask<String, Integer, JSONObject>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
str_Device_IP_Address=sharedPref1.getString("ip_address", "a\n");
System.out.println("strCode in Gsk_Demo ="+str_Device_IP_Address);
strUserName = etextUsername.getText().toString().trim();
strPassWord = etextPassword.getText().toString().trim();
pDialog = new ProgressDialog(Login.this);
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
System.out.println("Progress Dialog!!!!!!!!!!!!!!!!!!!!!!!");
}
#Override
protected JSONObject doInBackground(String... args)
{
String strUrl = "http://test.xxxxxx.com/cms/json/w2iWS";
JSONParser jParser = new JSONParser();
Log.e("DoinBackground !!!!!","Method");
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(strUrl);
String jsonString=json.toString();
Log.e("jsonString in DoinBackground !!!!!","Method" + jsonString);
return json;
}
#Override
protected void onPostExecute(JSONObject json)
{
pDialog.dismiss();
try
{
// Getting JSON Array
user = json.getJSONArray( KEY_REQUEST_ID );
JSONObject jsonObject = user.getJSONObject(0);
jsonObject.put(KEY_REQUEST_CODE, RequestCode);
jsonObject.put(KEY_CHANNEL_ID, stringChannelId);
jsonObject.put(KEY_IP_ADDRESS, str_Device_IP_Address);
jsonObject.put(KEY_USERNAME, strUserName);
jsonObject.put(KEY_PASSWORD, strPassWord);
String encrypted1 = EncodeDecodeAES.encrypt(jsonObject.toString(), textToEncrypt);
System.out.println("encrypted1 =" + encrypted1);
JSONObject inner = new JSONObject();
inner.put(KEY_REQUEST, encrypted1);
inner.put(KEY_VENDOR_ID, "1");
String decrypted = EncodeDecodeAES.decrypt(jsonObject.toString(), encrypted);
System.out.println("decrypted =" + decrypted);
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
GetJSONParse getjsonparse = new GetJSONParse();
getjsonparse.execute();
}
// Get Ip Address
private void connectWithHttpGet_IpAddress() {
class httpGetAsynchTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
String url = "http://api.externalip.net/ip";
Log.e("!!STRING URL DATE DETAIL", "" + url);
HttpGet httpGet = new HttpGet(url);
Log.e("", "" + httpGet);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
Log.e("HTTP.RESPONSE.DATE.DTAIL", "" + httpResponse);
System.out.println("HTTPRESPONSE");
InputStream inpustream = httpResponse.getEntity()
.getContent();
InputStreamReader inputstreamreader = new InputStreamReader(
inpustream);
BufferedReader bufferedreader = new BufferedReader(
inputstreamreader);
StringBuilder stringbuilder = new StringBuilder();
Log.e("", "" + stringbuilder);
String strbuffer = null;
while ((strbuffer = bufferedreader.readLine()) != null)
{
stringbuilder.append(strbuffer);
}
String strResponse = stringbuilder.toString();
/****************** Code For Shared Preferences **************************************/
sharedPref1 = getSharedPreferences(pref_filename, 0);
editor = sharedPref1.edit();
editor.putString("ip_address", strResponse);
Log.e("Returning value of doInBackground REsponse:" ,strResponse);
System.out.println("IPADDRESS IN DOIN BACKGRAOUND");
editor.commit();
/***************** Code For Shared Preferences **************************************/
}
catch (ClientProtocolException cpe) {
cpe.printStackTrace();
Log.e("Exception generates caz of httpResponse :", "-"
+ cpe);
}
catch (IOException ioe) {
ioe.printStackTrace();
Log.e("Second exception generates caz of httpResponse :",
"-" + ioe);
}
return null;
}
}
httpGetAsynchTask httpGetAsyncTask = new httpGetAsynchTask();
httpGetAsyncTask.execute();
}
public static void showNoConnectionDialog(final Login login)
{
AlertDialog.Builder builder = new AlertDialog.Builder(login);
builder.setCancelable(true);
builder.setMessage(R.string.no_connection);
builder.setTitle(R.string.no_connection_title);
builder.setPositiveButton(R.string.settings_button_text, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
login.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton(R.string.cancel_button_text, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
#Override
public void onCancel(DialogInterface dialog) {
return;
}
});
builder.show();
}
public boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected())
{
return true;
}
else
{
return false;
}
}
}
Asynctask is not invoked
JSONParse jp =new JSONParse();
jp.execute(params);
http://developer.android.com/reference/android/os/AsyncTask.html
public final AsyncTask<Params, Progress, Result> execute (Params... params)
Executes the task with the specified parameters.
You had no invoked asynctask before
GetJSONParse get = new GetJSONParse();
get.execute(params);
And you said i can't see the log message in doInbackground. i just ran your code and i can see the log

Categories