Concatenation inside try catch - android

try {
final List<NetworkType> dataReceived = getData();
int i = 0;
//Array Iteration
for(final NetworkType networkType : dataReceived) {
i++;
if (i > 3) {
Toast.makeText(getApplicationContext(), "Done!!", Toast.LENGTH_SHORT);
} else {
String mCell1CID = networkType.getCell1CID();
String mCell1LAC = networkType.getCell1LAC();
String mCell1MCC = networkType.getCell1MCC();
String mCell1MNC = networkType.getCell1MNC();
String mCell1CI = networkType.getCell1CI();
String mCell1TAC = networkType.getCell1TAC();
//API requestBody
String url = "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyA8NAA3dUpECFn2j6pdcQT3wgqUM98UZ2Q";
String cellID = null;
String locationAreaCode = null;
if (mCell1CID.equals("") && mCell1LAC.equals("")) {
cellID = mCell1CI;
locationAreaCode = mCell1TAC;
} else if (mCell1CI.equals("") && mCell1TAC.equals("")) {
cellID = mCell1CID;
locationAreaCode = mCell1LAC;
} else {
Log.d("GeoL", "3");
}
String requestBody =
"{" +
"\"cellTowers\":[" +
"{" +
"\"cellId\" :" + cellID + "," +
"\"locationAreaCode\" :" + locationAreaCode + "," +
"\"mobileCountryCode\" :" + "\"" + mCell1MCC + "\"" + "," +
"\"mobileNetworkCode\" :" + "\"" + mCell1MNC + "\"" +
"}" +
"]" +
"}";
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, url, requestBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(String.valueOf(response));
JSONObject latitude = jsonObject.getJSONObject("location");
String lat = latitude.getString("lat");
String lng = latitude.getString("lng");
String acc = jsonObject.getString("accuracy");
if (!dataReceived.listIterator().hasNext()){
String print;
print = String.format("%s%s", print, print(lat.toString(), lng.toString(), acc.toString()));
writeToFile(print, getApplicationContext());
} else {
String print;
print = String.format("%s%s,", print, print(lat.toString(), lng.toString(), acc.toString()));
writeToFile(print, getApplicationContext());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Response", "error" + error.toString());
}
});
queue.add(jsObjRequest);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I need to concat the received value to the print variable.
But this the error which i receive
print needs to be initialized is what I receive.
also if declared outside the try/catch block it requires it to be final.
What to do?

just use String print = null; when you declare print

You are providing a value that is not initialized to the String.format
You need to initialize the variable "print" with what you want to be used in the String.format (for example an empty String) :
String print= ""
Or use String Builder:
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("1");
stringBuilder.append("2");
String finalString = stringBuilder.toString();

Related

how to merge 2 data records to one in a recyclerView ? (mysql & volley)

I want to merge two data records to become one based on the same DAY, but different "Sesi" such as Sesi 1, and Sesi 2 being 1 in a recyclerVCiew
please see my application Image
here I use mySql with volley JSON + Inner Join MYSQL
Main Activity:
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_ALL_JADWAL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject jadwal = array.getJSONObject(i);
String kelas = jadwal.getString("Kelas");
if (kelas.equals(Kelas)) {
jadwalHarianList.add(new JadwalHarian(
jadwal.getString("Nama_Pengajar"),
jadwal.getString("Mata_Kuliah"),
jadwal.getString("Ruang"),
jadwal.getInt("Sesi"),
jadwal.getString("Hari"),
jadwal.getString("Jam")
));
}
JadwalRV jadwalRV = new JadwalRV(getApplicationContext(), jadwalHarianList);
recyclerView.setAdapter(jadwalRV);
jadwalRV.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
JadwalRV Adapter:
public void onBindViewHolder(JadwalRV.MyViewHolder myViewHolder, int i) {
JadwalHarian jadwalHarian = mJadwalHarian.get(i);
myViewHolder.tHari.setText(jadwalHarian.getHari());
myViewHolder.tIsi.setText("Waktu\n" +
"Ruang\n" +
"Mata Kuliah\n" +
"Dosen Pengajar");
myViewHolder.thjam.setText(
"= " + jadwalHarian.getJam()+
"\n= " + jadwalHarian.getRuang() +
"\n= " + jadwalHarian.getMata_Kuliah() +
"\n= " + jadwalHarian.getNama_Pengajar() );
// SESI 2
myViewHolder.tIsi2.setText("Waktu\n" +
"Ruang\n" +
"Mata Kuliah\n" +
"Dosen Pengajar");
myViewHolder.thjam2.setText(
"= " + jadwalHarian.getJam()+
"\n= " + jadwalHarian.getRuang() +
"\n= " + jadwalHarian.getMata_Kuliah() +
"\n= " + jadwalHarian.getNama_Pengajar() );
}
Here is Structure Table which I used inner join in my PHP json
You can try like this following not obvious, but It can help you:
try
{
JSONArray array = new JSONArray();
ArrayList<HashMap<String,Object>> jadwalHarianList = new ArrayList<>();
JSONObject jsonObject=new JSONObject();
try
{
jsonObject.put("Kelas", "R28");
jsonObject.put("Sesi", "1");
jsonObject.put("Mata_Kuliah", "Pemprograman #1");
array.put(jsonObject);
jsonObject = new JSONObject();
jsonObject.put("Kelas", "R28");
jsonObject.put("Sesi", "2");
jsonObject.put("Mata_Kuliah", "Algoritma #2");
array.put(jsonObject);
}
catch (Exception e)
{
Log.e("ldfjdlfj","data----111_jsonOb_ex>>>"+e);
}
Log.e("ldfjdlfj","data----2222>>>"+array);
String previous = "";
for (int i = 0; i < array.length(); i++) {
JSONObject jadwal = array.getJSONObject(i);
String kelas = jadwal.getString("Kelas");
String Sesi = jadwal.getString("Sesi");
String Mata_Kuliah = jadwal.getString("Mata_Kuliah");
if(kelas.equalsIgnoreCase(previous))
{
HashMap<String,Object> map = new HashMap<>();
map.put("kelas",array.getJSONObject(i-1).getString("Kelas"));
map.put("Sesi",array.getJSONObject(i-1).getString("Sesi"));
map.put("Sesi2",Sesi);
map.put("Mata_Kuliah",Mata_Kuliah);
jadwalHarianList.add(map);
}
else
{
previous = kelas;
HashMap<String,Object> map = new HashMap<>();
map.put("kelas",array.getJSONObject(i).getString("Kelas"));
map.put("Sesi",array.getJSONObject(i).getString("Sesi"));
map.put("Sesi2","");
map.put("Mata_Kuliah",Mata_Kuliah);
jadwalHarianList.add(map);
}
}
Log.e("ldfjdlfj","data----333_>>>"+jadwalHarianList);
} catch (JSONException e) {
e.printStackTrace();
}

How to update the Recylerview View items after displayed First Json URL In android

I having a problem update the Item in Recycler View.I will explain clearly about my problem.
I am using two Json URL's first Json URL can send the items to model class.
after completed this called the adapter, then update the second Json URL items with the adapter by using setter model class.
so that's why called adapter.notifyitemchanged, but only one time can updated items next time while looping doesn't update the items display empty for second time.
Code:
public void servicecallsingle(String list, final int pin) {
url = Constants.singleproducturl + list;
JsonObjectRequest request1 = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
#Override
public void onResponse(JSONObject response) {
JSONObject response1 = response;
if (response1 != null) {
// int status=jsonObject.optInt("status");
String status = response1.optString("status");
if (status.equalsIgnoreCase("200")) { //check the status 200 or not
try {
productpath = response1.getString("productPath");
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject responses = response1.getJSONObject("response");
jsonarray = responses.getJSONArray(DATA);
if (jsonarray.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < jsonarray.length(); i++) {
item = new CartItemoriginal();
JSONObject product = jsonarray.getJSONObject(i);
cartpid = product.getString("product_id");
cartproductname = product.getString("product_name");
cartaliasname = product.getString("product_alias");
cartprice = product.getString("mrp_price");
String sp = product.getString("selling_price");
String op = product.getString("offer_selling_price");
sellerid = product.getString("seller_id");
JSONArray pimg = product.getJSONArray("product_images");
JSONObject firstimg = pimg.getJSONObject(0);
cartimg = firstimg.getString("original_res");
String[] img2 = cartimg.split("\\.");
String imagone = productpath + sellerid + '/' + img2[0] + '(' + '2' + '0' + '0' + ')' + '.' + img2[1];
String Quantity = product.getString("product_max_add");
String minqty = product.getString("product_min_add");
int qty = Integer.parseInt(Quantity);
/*** calculation ***/
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
int ts1 = Integer.parseInt(ts);
String startdate1 = product.getString("offer_selling_start_date");
String endate1 = product.getString("offer_selling_end_date");
if (("".equals(startdate1)) && ("".equals(endate1))) {
// Toast.makeText(getActivity(),"wrong statemnt",Toast.LENGTH_LONG).show();
if (cartprice.equalsIgnoreCase(sp)) {
double d = Double.parseDouble(cartprice);
int mrp = (int) d;
price = String.valueOf(mrp);
} else {
double s = Double.parseDouble(sp);
int sales = (int) s;
price = String.valueOf(sales);
}
} else {
int startdate = Integer.parseInt(startdate1);
int endate2 = Integer.parseInt(endate1);
if (ts1 > startdate && ts1 < endate2) {
double offer = Double.parseDouble(op);
int offers = (int) offer;
price = String.valueOf(offers);
} else {
if (cartprice.equalsIgnoreCase(sp)) {
double d = Double.parseDouble(cartprice);
int mrp = (int) d;
price = String.valueOf(mrp);
} else {
double s = Double.parseDouble(sp);
int sales = (int) s;
price = String.valueOf(sales);
}
}
}
item.setProductname(cartproductname);
item.setQty(1);
item.setProductimg(imagone);
item.setMaxquantity(Quantity);
item.setAliasname(cartaliasname);
item.setPrice(price);
item.setMinquantity(minqty);
item.setProductid(cartpid);
cart.add(item);
// cart.add(new CartItemoriginal(imagone,cartproductname,cartaliasname,1,Quantity,minqty,price,cartpid));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} // condtion check the status 200
else // this is if status falied in runtime
{
Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show();
}
// llm = new LinearLayoutManager(CartItems.this);
MainLinear.setVisibility(View.VISIBLE);
final CustomLinearLayoutManagercartpage layoutManager = new CustomLinearLayoutManagercartpage(CartItems.this, LinearLayoutManager.VERTICAL, false);
recyleitems.setHasFixedSize(false);
recyleitems.setLayoutManager(layoutManager);
cartadapter = new CartlistAdapter(cart, CartItems.this);
Log.i(String.valueOf(cartadapter), "cartadapter");
recyleitems.setAdapter(cartadapter);
recyleitems.setNestedScrollingEnabled(false);
myView.setVisibility(View.GONE);
cartadapter.notifyDataSetChanged();
}
String id = cartpid;
String selleid = sellerid;
final int pinnum = pin;
String pinurl = "http://192.168.0.33/sharpswebsite3/qcrest1.0/?type=pinCodeCheck&result=json&product_id=" + id + "&seller_id=" + selleid + "&pinCode=" + pinnum;
JsonObjectRequest request2 = new JsonObjectRequest(Request.Method.GET, pinurl, null, new Response.Listener < JSONObject > () {
#Override
public void onResponse(JSONObject responsesecond) {
JSONObject response2 = responsesecond;
// do something with response1 & response here...
if (response2 != null) {
// int status=jsonObject.optInt("status");
String status = response2.optString("status");
if (status.equalsIgnoreCase("200")) { //check the status 200 or not
try {
JSONObject responses = response2.getJSONObject("response");
jsonarray = responses.getJSONArray(DATA);
if (jsonarray.length() > 0) {
Log.i(String.valueOf(jsonarray.length()), "message");
// looping through json and adding to movies list
for (int j = 0; j < jsonarray.length(); j++) {
JSONObject product = jsonarray.getJSONObject(j);
process = product.getString("process");
Message = product.getString("message");
if (process.equalsIgnoreCase("success") && Message.equalsIgnoreCase("success")) {
cartdelivery = product.getString("delivery");
cartshippingcharge = product.getString("shipping_charge");
String pincode = product.getString("pincode");
/**************************calculation of shipping days**************************/
int day = Integer.parseInt(cartdelivery);
Calendar c = Calendar.getInstance();
String dayNumberSuffix = getDayNumberSuffix(day);
SimpleDateFormat sdf = new SimpleDateFormat(" MMM d'" + dayNumberSuffix + "', yyyy");
String currentDateandTime = sdf.format(new Date());
try {
c.setTime(sdf.parse(currentDateandTime));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DATE, day);
Date resultdate = new Date(c.getTimeInMillis());
currentDateandTime = sdf.format(resultdate);
Log.d(String.valueOf(currentDateandTime), "shipping days");
cart.get(j).setDelivery("Standard delivery by" + " " + currentDateandTime);
cart.get(j).setShippincharge(cartshippingcharge);
cart.get(j).setSellername("richard feloboune");
cartadapter.notifyItemChanged(j);
cartadapter.notifyItemRangeChanged(j, cart.size());
} else {
// cart2.add(new Cartitemoringinaltwo("Seller doesn't deliver to this item to"+" "+ String.valueOf(pinnum)));
cart.get(j).setError("Seller doesn't deliver to this item to" + " " + String.valueOf(pinnum));
cartadapter.notifyItemChanged(j);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// stopping swipe refresh
// swipeRefreshLayout.setRefreshing(false);
} // condtion check the status 200
else // this is if status falied in runtime
{
Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show();
}
}
pincheck();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("onErrorResponse", error.toString());
}
});
AppController.getInstance().addToRequestQueue(request2);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("onErrorResponse", error.toString());
}
});
AppController.getInstance().addToRequestQueue(request1);
}
Note: While looping first time can set the item in setter model class but second couldn't set the item to model class.
Anyone solve this problem glad to appreciate.
Thanks in advance
The problem is volley doesn't wait for the request to be completed. So as the first call is made within seconds other call will be also made. So, you need to create an interface which will be called when the first webservice is called, and than in interface call other webservice and than notifyDataSet.
public void servicecallsingle(String list, final int pin) {
url = Constants.singleproducturl + list;
JsonObjectRequest request1 = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
#Override
public void onResponse(JSONObject response) {
JSONObject response1 = response;
if (response1 != null) {
// int status=jsonObject.optInt("status");
String status = response1.optString("status");
if (status.equalsIgnoreCase("200")) { //check the status 200 or not
try {
productpath = response1.getString("productPath");
} catch (JSONException e) {
e.printStackTrace();
}
parseJson(response1, new WebServiceCallBack{
public void getWebserviceCallBack(){
// Call another webservice here
String id = cartpid;
String selleid = sellerid;
final int pinnum = pin;
String pinurl = "http://192.168.0.33/sharpswebsite3/qcrest1.0/?type=pinCodeCheck&result=json&product_id=" + id + "&seller_id=" + selleid + "&pinCode=" + pinnum;
JsonObjectRequest request2 = new JsonObjectRequest(Request.Method.GET, pinurl, null, new Response.Listener < JSONObject > () {
#Override
public void onResponse(JSONObject responsesecond) {
JSONObject response2 = responsesecond;
// do something with response1 & response here...
if (response2 != null) {
// int status=jsonObject.optInt("status");
String status = response2.optString("status");
if (status.equalsIgnoreCase("200")) { //check the status 200 or not
try {
JSONObject responses = response2.getJSONObject("response");
jsonarray = responses.getJSONArray(DATA);
if (jsonarray.length() > 0) {
Log.i(String.valueOf(jsonarray.length()), "message");
// looping through json and adding to movies list
for (int j = 0; j < jsonarray.length(); j++) {
JSONObject product = jsonarray.getJSONObject(j);
process = product.getString("process");
Message = product.getString("message");
if (process.equalsIgnoreCase("success") && Message.equalsIgnoreCase("success")) {
cartdelivery = product.getString("delivery");
cartshippingcharge = product.getString("shipping_charge");
String pincode = product.getString("pincode");
/**************************calculation of shipping days**************************/
int day = Integer.parseInt(cartdelivery);
Calendar c = Calendar.getInstance();
String dayNumberSuffix = getDayNumberSuffix(day);
SimpleDateFormat sdf = new SimpleDateFormat(" MMM d'" + dayNumberSuffix + "', yyyy");
String currentDateandTime = sdf.format(new Date());
try {
c.setTime(sdf.parse(currentDateandTime));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DATE, day);
Date resultdate = new Date(c.getTimeInMillis());
currentDateandTime = sdf.format(resultdate);
Log.d(String.valueOf(currentDateandTime), "shipping days");
cart.get(j).setDelivery("Standard delivery by" + " " + currentDateandTime);
cart.get(j).setShippincharge(cartshippingcharge);
cart.get(j).setSellername("richard feloboune");
cartadapter.notifyItemChanged(j);
cartadapter.notifyItemRangeChanged(j, cart.size());
} else {
// cart2.add(new Cartitemoringinaltwo("Seller doesn't deliver to this item to"+" "+ String.valueOf(pinnum)));
cart.get(j).setError("Seller doesn't deliver to this item to" + " " + String.valueOf(pinnum));
cartadapter.notifyItemChanged(j);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// stopping swipe refresh
// swipeRefreshLayout.setRefreshing(false);
} // condtion check the status 200
else // this is if status falied in runtime
{
Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show();
}
}
pincheck();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("onErrorResponse", error.toString());
}
});
AppController.getInstance().addToRequestQueue(request2);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("onErrorResponse", error.toString());
}
});
AppController.getInstance().addToRequestQueue(request1);
});
}
} // condtion check the status 200
else // this is if status falied in runtime
{
Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show();
}
// llm = new LinearLayoutManager(CartItems.this);
MainLinear.setVisibility(View.VISIBLE);
final CustomLinearLayoutManagercartpage layoutManager = new CustomLinearLayoutManagercartpage(CartItems.this, LinearLayoutManager.VERTICAL, false);
recyleitems.setHasFixedSize(false);
recyleitems.setLayoutManager(layoutManager);
cartadapter = new CartlistAdapter(cart, CartItems.this);
Log.i(String.valueOf(cartadapter), "cartadapter");
recyleitems.setAdapter(cartadapter);
recyleitems.setNestedScrollingEnabled(false);
myView.setVisibility(View.GONE);
cartadapter.notifyDataSetChanged();
}
public void parseJson(JSONObject response1, WebServiceCallBack webserviceCallBack){
try {
JSONObject responses = response1.getJSONObject("response");
jsonarray = responses.getJSONArray(DATA);
if (jsonarray.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < jsonarray.length(); i++) {
item = new CartItemoriginal();
JSONObject product = jsonarray.getJSONObject(i);
cartpid = product.getString("product_id");
cartproductname = product.getString("product_name");
cartaliasname = product.getString("product_alias");
cartprice = product.getString("mrp_price");
String sp = product.getString("selling_price");
String op = product.getString("offer_selling_price");
sellerid = product.getString("seller_id");
JSONArray pimg = product.getJSONArray("product_images");
JSONObject firstimg = pimg.getJSONObject(0);
cartimg = firstimg.getString("original_res");
String[] img2 = cartimg.split("\\.");
String imagone = productpath + sellerid + '/' + img2[0] + '(' + '2' + '0' + '0' + ')' + '.' + img2[1];
String Quantity = product.getString("product_max_add");
String minqty = product.getString("product_min_add");
int qty = Integer.parseInt(Quantity);
/*** calculation ***/
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
int ts1 = Integer.parseInt(ts);
String startdate1 = product.getString("offer_selling_start_date");
String endate1 = product.getString("offer_selling_end_date");
if (("".equals(startdate1)) && ("".equals(endate1))) {
// Toast.makeText(getActivity(),"wrong statemnt",Toast.LENGTH_LONG).show();
if (cartprice.equalsIgnoreCase(sp)) {
double d = Double.parseDouble(cartprice);
int mrp = (int) d;
price = String.valueOf(mrp);
} else {
double s = Double.parseDouble(sp);
int sales = (int) s;
price = String.valueOf(sales);
}
} else {
int startdate = Integer.parseInt(startdate1);
int endate2 = Integer.parseInt(endate1);
if (ts1 > startdate && ts1 < endate2) {
double offer = Double.parseDouble(op);
int offers = (int) offer;
price = String.valueOf(offers);
} else {
if (cartprice.equalsIgnoreCase(sp)) {
double d = Double.parseDouble(cartprice);
int mrp = (int) d;
price = String.valueOf(mrp);
} else {
double s = Double.parseDouble(sp);
int sales = (int) s;
price = String.valueOf(sales);
}
}
}
item.setProductname(cartproductname);
item.setQty(1);
item.setProductimg(imagone);
item.setMaxquantity(Quantity);
item.setAliasname(cartaliasname);
item.setPrice(price);
item.setMinquantity(minqty);
item.setProductid(cartpid);
cart.add(item);
// cart.add(new CartItemoriginal(imagone,cartproductname,cartaliasname,1,Quantity,minqty,price,cartpid));
}
}
} catch (JSONException e) {
e.printStackTrace();}
webserviceCallBack.getWebserviceCallBack();
}
public interface WebServiceCallBack{
public void getWebserviceCallBack()
}

Calling a method on android button click

I am trying to make a web service call via android button click. I've managed to rectify the errors, but it shows some bugs on getting response. I receive null response. Below is my code. Could someone debug me please..!
My code:
refresh_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
HttpHandler httpHandler1 = new HttpHandler();
String res = null;
String authToken = "MlSyULrWlFgVk28";
try {
Log.d("edwLog", TAG + " get_payment_notifications " + HttpHandler.API_URL + "get_payment_notifications/" + authToken + "/");
res = httpHandler1.makeServiceCall(HttpHandler.API_URL + "get_payment_notifications/" + authToken + "/", HttpHandler.GET);
Log.d("edwLog", TAG + " response > " + res);
if (res != null) {
JSONObject jsonObject = new JSONObject(res);
String responseType = jsonObject.getString("type");
if (responseType.equals("success")) {
if (jsonObject.has("response")) {
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
notifications.add(jsonArray.getJSONObject(i));
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
Log.d("edwLog", TAG + " IOException > " + e.toString());
}
}
});
Are you getting compile time error or runtime. It seems that you are trying to return a bundle from a method that has a return type void i.e.
public void onClick(View v)
Found the bug..! The mistake was, I had passed the AuthToken as a default String. Now I declared it as "null" in final, i.e., before onCreate and deleted it from inside the ClickEvent. And its done.. The right code below..
refresh_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
HttpHandler httpHandler1 = new HttpHandler();
String res = null;
try {
Log.d("edwLog", TAG + " get_payment_notifications " + HttpHandler.API_URL + "get_payment_notifications/" + AuthToken + "/");
res = httpHandler1.makeServiceCall(HttpHandler.API_URL + "get_payment_notifications/" + AuthToken + "/", HttpHandler.GET);
Log.d("edwLog", TAG + " response > " + res);
if (res != null) {
JSONObject jsonObject = new JSONObject(res);
String responseType = jsonObject.getString("type");
if (responseType.equals("success")) {
if (jsonObject.has("response")) {
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
notifications.add(jsonArray.getJSONObject(i));
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
Log.d("edwLog", TAG + " IOException > " + e.toString());
}
}
});

How do I structure my data to switch from using ParseJsonArray/ParseJsonObject to using GSON.fromJson(...)

I have been working with GSON to try and parse a Json response I am getting from a CakePHP server for about a week. Here is what the response looks like :
[{"BaseObject": {"field1":"1","field2":"1639","field3":"10","field4":"1","field5":"12","field6":"10.765984","field7":"-25.768357","field8":"1327790850"}},{"BaseObject":{"field1":"2","field2":"1934","field3":"19","field4":"30","field5":"2","field6":"10.758662","field7":"-25.769684","field8":"1327790850"}},{"BaseObject":{"field1":"3","field2":"2567","field3":"33","field4":"6","field5":"98","field6":"10.758786","field7":"-25.769843","field8":"1327790850"}},{"BaseObject":{"field1":"4","field2":"0","field3":"33","field4":"7","field5":"0","field6":"10.758786","field7":"-20.769843","field8":"1327790850"}},{"BaseObject":{"field1":"5","field2":"1097","field3":"33","field4":"1","field5":"0","field6":"15.758786","field7":"50.769843","field8":"1327790850"}},{"BaseObject":{"field1":"6","field2":"1936","field3":"50","field4":"0","field5":"9","field6":"19.234987","field7":"-67.340065","field8":"1327798560"}}]
I used a plugin for Notepad++ to verify that the response is valid Json and it is.
First I tried this function:
public static List<BaseObject> parserInputStreamGson(InputStream stream)
{
List<BaseObject> objList = new ArrayList<BaseObject>();
if(stream != null){
Gson gson = new Gson();
Reader r = new InputStreamReader(stream);
Log.d(TAG,"Trying to Parse Reader");
try{
objList = gson.fromJson(r, new TypeToken<List<BaseObject>>() {}.getType() );
} catch (JsonSyntaxException e) {
Log.d(TAG, "JsonSyntaxException : " + e.getMessage() );
} catch (JsonIOException e) {
Log.d(TAG, "JsonIOException : " + e.getMessage() );
} finally {
try {
r.close();
} catch (IOException e) {
Log.d(TAG, "IOException : " + e.getMessage() );
}
}
}
Log.d(TAG,"BaseObject[] = " + objList.toString());
return objList;
}
Then I tried this function:
public static BaseObject[] parserInputStreamGsonArray(InputStream stream)
{
BaseObject[] objectArray = null;
if (stream != null) {
Gson gson = new Gson();
Reader r = new InputStreamReader(stream);
Log.d(TAG, "Trying to Parse Reader");
try {
objectArray = gson.fromJson(r, new TypeToken<Event[]>() {}.getType());
} catch (JsonSyntaxException e) {
Log.d(TAG, "JsonSyntaxException : " + e.getMessage());
} catch (JsonIOException e) {
Log.d(TAG, "JsonIOException : " + e.getMessage());
} finally {
try {
r.close();
} catch (IOException e) {
Log.d(TAG, "IOException : " + e.getMessage());
}
}
}
if(eventArray != null){
for(int m=0;m<eventArray.length;m++){
Log.d(TAG, "objectArray[" + String.valueOf(m) + "] = " + objectArray[m].toString());
}
}
return objectArray;
}
And in both cases Gson returned 5 objects, but all of the fields were set to zero.
Finally I got this function to work, but it feels clunky.
public static List<BaseObject> ParseInputStream(InputStream stream) {
Reader r = new InputStreamReader(stream);
List<BaseObject> baseObjectList = new ArrayList<BaseObject>();
try {
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(r).getAsJsonArray();
JsonObject topObject = new JsonObject();
JsonObject subObject = new JsonObject();
for (int m = 0; m < array.size(); m++) {
if (array.get(m).isJsonObject()) {
topObject = array.get(m).getAsJsonObject();
if (topObject.get("BaseObject").isJsonObject()) {
subObject = topObject.get("BaseObject").getAsJsonObject();
BaseObject baseobject = new BaseObject();
baseobject.field1 = subObject.get("field1").getAsLong();
baseobject.field2 = subObject.get("field2").getAsInt();
baseobject.field3 = subObject.get("field3").getAsLong();
baseobject.field4 = subObject.get("field4").getAsInt();
baseobject.field5 = subObject.get("field5").getAsInt();
baseobject.field6 = subObject.get("field6").getAsDouble();
baseobject.field7 = subObject.get("field7").getAsDouble();
baseobject.field8 = subObject.get("field8").getAsLong();
baseObjectList.add(baseobject);
} else {
Log.e(TAG, "topObject[" + String.valueOf(m)+ "].subObject is not a JsonObject");
}
} else {
Log.e(TAG, "Array # " + String.valueOf(m)+ " is not a JsonObject!");
}
}
} catch (Exception ex) {
Log.e(TAG, "Exception thrown = " + ex.toString());
ex.printStackTrace();
}
return baseObjectList;
}
Here is the class I created for BaseObject.
public class BaseObject {
#SerializedName("field1")
public long field1;
#SerializedName("field2")
public int field2;
#SerializedName("field3")
public long field3;
#SerializedName("field4")
public int field4;
#SerializedName("field5")
public int field5;
#SerializedName("field6")
public double field6;
#SerializedName("field7")
public double field7;
#SerializedName("field8")
public long field8;
#Override
public String toString() {
return "(" +
"field1= " + String.valueOf(this.field1) + ", " +
"field2= " + String.valueOf(this.field2) + ", " +
"field3= " + String.valueOf(this.field3) + ", " +
"field4= " + String.valueOf(this.field4) + ", " +
"field5= " + String.valueOf(this.field5) + ", " +
"field6= " + String.valueOf(this.field6) + ", " +
"field7= " + String.valueOf(this.field7) + ", " +
"field8= " + String.valueOf(this.field8) +
")";
}
}
Can anyone tell me how I need to structure my data classes in order use Gson.fromJson to work.
Since your response is actually List<BaseObject>, you should be using
List baseObjectList = new Gson().fromJson(r,new TypeToken>() {}.getType())
Also I should mention that, you do not really need to use the #SerializedName annotations since your attribute names in the json reply and in the class are same.
UPDATE:
Oops.. Sorry, I should have tried your code before answering. Please refer to the following code. Everything boiled down to the Structuring of classes.
public class Sample {
public static class Wrapper{
private BaseObject BaseObject;
#Override
public String toString() {
return BaseObject == null? null : BaseObject.toString();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String json = "[{\"BaseObject\": {\"field1\":\"1\",\"field2\":\"1639\",\"field3\":\"10\",\"field4\":\"1\",\"field5\":\"12\",\"field6\":\"10.765984\",\"field7\":\"-25.768357\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"2\",\"field2\":\"1934\",\"field3\":\"19\",\"field4\":\"30\",\"field5\":\"2\",\"field6\":\"10.758662\",\"field7\":\"-25.769684\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"3\",\"field2\":\"2567\",\"field3\":\"33\",\"field4\":\"6\",\"field5\":\"98\",\"field6\":\"10.758786\",\"field7\":\"-25.769843\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"4\",\"field2\":\"0\",\"field3\":\"33\",\"field4\":\"7\",\"field5\":\"0\",\"field6\":\"10.758786\",\"field7\":\"-20.769843\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"5\",\"field2\":\"1097\",\"field3\":\"33\",\"field4\":\"1\",\"field5\":\"0\",\"field6\":\"15.758786\",\"field7\":\"50.769843\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"6\",\"field2\":\"1936\",\"field3\":\"50\",\"field4\":\"0\",\"field5\":\"9\",\"field6\":\"19.234987\",\"field7\":\"-67.340065\",\"field8\":\"1327798560\"}}]";
List<Wrapper> results = new Gson().fromJson(json,new TypeToken<List<Wrapper>>(){}.getType());
System.out.println(results);
}
}
Just curious, do you have the liberty to change the JSON reply coming from server? IMHO, Its structure is a little complicated.

Import yahoo contacts into android application

Hey anybody can tell me how can i import all yahoo contacts into my android application please , show me proper way dont give me yahoo api etc if u have source code kindly post it
thank you
just create a layout with webview , and use this code to get contacts.
you need oauth libraries,. and replace consumer key and scret with yours.
public class YahooContacts extends BaseActivity {
private final String TAG = "yahoo_auth";
private static final String CONSUMER_KEY = "you_consumer_key";
private static final String CONSUMER_SECRET = "your_consumer_secret";
private static final String CALLBACK_SCHEME = "http";
private static final String CALLBACK_HOST = "www.blablablao.com";
private static final String CALLBACK_URL = CALLBACK_SCHEME + "://"
+ CALLBACK_HOST;
private String AUTH_TOKEN = null;
private String AUTH_TOKEN_SECRET = null;
private String AUTH_URL = null;
private String USER_TOKEN = null;
private String ACCESS_TOKEN = null;
private String ACCESS_TOKEN_SECRET = null;
private String mUSER_GUID = null;
private WebView mWebview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yahoo_layout);
mWebview = (WebView) findViewById(R.id.webview);
new getContactsTask().execute();
}
class getContactsTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
getAuthorizationToken();
getUserAutherization();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
private void getAuthorizationToken() {
String requestPath = "https://api.login.yahoo.com/oauth/v2/get_request_token?oauth_consumer_key="
+ CONSUMER_KEY
+ "&oauth_nonce="
+ System.currentTimeMillis()
+ "x"
+ "&oauth_signature_method=PLAINTEXT"
+ "&oauth_signature="
+ CONSUMER_SECRET
+ "%26"
+ "&oauth_timestamp="
+ System.currentTimeMillis()
+ "&oauth_version=1.0"
+ "&xoauth_lang_pref=en-us"
+ "&oauth_callback=" + CALLBACK_URL;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(requestPath);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
String[] data = responseBody.split("&");
AUTH_TOKEN = data[0].replace("oauth_token=", "");
AUTH_TOKEN_SECRET = data[1].replace("oauth_token_secret=", "");
AUTH_URL = data[3].replace("xoauth_request_auth_url=", "");
VIPLogger.info(TAG, "authToken" + AUTH_TOKEN);
VIPLogger.info(TAG, "authToken secret" + AUTH_TOKEN_SECRET);
} catch (Exception e) {
e.printStackTrace();
}
}
private void getUserAutherization() {
mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.setWebViewClient(lWebviewClient);
mWebview.loadUrl("https://api.login.yahoo.com/oauth/v2/request_auth?oauth_token="
+ AUTH_TOKEN);
}
private void getAccessToken() {
String requestPath = "https://api.login.yahoo.com/oauth/v2/get_token?oauth_consumer_key="
+ CONSUMER_KEY
+ "&oauth_nonce="
+ System.currentTimeMillis()
+ "x"
+ "&oauth_signature_method=PLAINTEXT"
+ "&oauth_signature="
+ CONSUMER_SECRET
+ "%26"
+ AUTH_TOKEN_SECRET
+ "&oauth_timestamp="
+ System.currentTimeMillis()
+ "&oauth_version=1.0"
+ "&oauth_token="
+ AUTH_TOKEN
+ "&oauth_verifier="
+ USER_TOKEN;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(requestPath);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
String[] data = responseBody.split("&");
ACCESS_TOKEN = data[0].replace("oauth_token=", "");
ACCESS_TOKEN_SECRET = data[1].replace("oauth_token_secret=", "");
mUSER_GUID = data[5].replace("xoauth_yahoo_guid=", "");
VIPLogger.info(TAG, "user guid: " + responseBody);
VIPLogger.info(TAG, "Access token: " + ACCESS_TOKEN);
getAllContacts();
} catch (Exception e) {
e.printStackTrace();
VIPLogger.error(TAG,
"error while fetching user guid and access token");
}
}
WebViewClient lWebviewClient = new WebViewClient() {
public void onPageStarted(WebView view, String url,
android.graphics.Bitmap favicon) {
if (url.contains("vipitservice")) {
mWebview.stopLoading();
int lastIndex = url.lastIndexOf("=") + 1;
VIPLogger.info(TAG, url.substring(lastIndex, url.length()));
USER_TOKEN = url.substring(lastIndex, url.length());
mWebview.setVisibility(View.GONE);
getAccessToken();
}
};
};
private void getAllContacts() {
HttpClient httpclient = new DefaultHttpClient();
String host_url = "http://social.yahooapis.com/v1/user/" + mUSER_GUID+ "/contacts";
String nonce = ""+System.currentTimeMillis();
String timeStamp = ""+(System.currentTimeMillis()/1000L);
try{
String params =
""+encode("oauth_consumer_key")+"=" + encode(CONSUMER_KEY)
+ "&"+encode("oauth_nonce")+"="+encode(nonce)
+ "&"+encode("oauth_signature_method")+"="+encode("HMAC-SHA1")
+ "&"+encode("oauth_timestamp")+"="+encode(timeStamp)
+ "&"+encode("oauth_token")+"="+ACCESS_TOKEN
+ "&"+encode("oauth_version")+"="+encode("1.0")
;
String baseString = encode("GET")+"&"+encode(host_url)+"&"+encode(params);
String signingKey = encode(CONSUMER_SECRET)+"&"+encode(ACCESS_TOKEN_SECRET);
VIPLogger.info(TAG, "base string: " + baseString);
String lSignature = computeHmac(baseString, signingKey);
VIPLogger.info(TAG, "signature: " + lSignature);
lSignature = encode(lSignature);
VIPLogger.info(TAG, "signature enacoded: " + lSignature);
String lRequestUrl = host_url
+ "?oauth_consumer_key="+CONSUMER_KEY
+ "&oauth_nonce="+nonce
+ "&oauth_signature_method=HMAC-SHA1"
+ "&oauth_timestamp="+timeStamp
+ "&oauth_token="+ACCESS_TOKEN
+ "&oauth_version=1.0"
+ "&oauth_signature="+lSignature
;
//VIPLogger.info(TAG, lRequestUrl.substring(1202));
HttpGet httpget = new HttpGet(lRequestUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
VIPLogger.info(TAG, "contacts response: " + responseBody);
}catch(Exception e){
e.printStackTrace();
VIPLogger.error(TAG, "error while fetching user contacts");
}
}
public String computeHmac(String baseString, String key) {
try {
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes("UTF-8"),
"HMAC-SHA1");
mac.init(signingKey);
byte[] digest = mac.doFinal(baseString.getBytes());
String result = Base64.encodeToString(digest, Base64.DEFAULT);
return result;
} catch (Exception e) {
e.printStackTrace();
VIPLogger.error(TAG, "error while generating sha");
}
return null;
}
public String encodeURIComponent(final String value) {
if (value == null) {
return "";
}
try {
return URLEncoder.encode(value, "utf-8")
// OAuth encodes some characters differently:
.replace("+", "%20").replace("*", "%2A")
.replace("%7E", "~");
// This could be done faster with more hand-crafted code.
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public String encode(String input) {
StringBuilder resultStr = new StringBuilder();
for (char ch : input.toCharArray()) {
if (isUnsafe(ch)) {
resultStr.append('%');
resultStr.append(toHex(ch / 16));
resultStr.append(toHex(ch % 16));
} else {
resultStr.append(ch);
}
}
return resultStr.toString().trim();
}
private char toHex(int ch) {
return (char) (ch < 10 ? '0' + ch : 'A' + ch - 10);
}
private boolean isUnsafe(char ch) {
if (ch > 128 || ch < 0)
return true;
return " %$&+,/:;=?#<>#%".indexOf(ch) >= 0;
}
}

Categories

Resources