How can i fix Missing required oauth parameter: oauth_signature_method? - android

I am trying to get the data from the Api but an error ocurred.
i have parameters like:
oauth_consumer_key- String --Your API key when you registered as a developer
oauth_signature_method- String-- The method used to generate the signature (only HMAC-SHA1 is supported)
oauth_timestamp -Int --The date and time, expressed in the number of seconds since January 1, 1970 00:00:00 GMT. The timestamp value must be a positive integer and must be equal or greater than the timestamp used in previous requests
oauth_nonce -String-- A randomly generated string for a request that can be combined with the timestamp to produce a unique value
oauth_version -String --MUST be "1.0"
oauth_signature- String-- The signature, a consistent reproducible concatenation of the request elements into a single string. The string is used as an input in hashing or signing algorithms.
method -String --MUST be "recipes.search"
and my class for this looks where i am using using Volley library to fetch the data:
final static private String APP_METHOD = "GET";
final static private String APP_KEY = "app key is here";
final static private String APP_SECRET = "secret key is here&";
final static private String APP_URL = "http://platform.fatsecret.com/rest/server.api";
private static final String HMAC_SHA1_ALGORITHM = "HMAC-SHA1";
private static String paramify(String[] params) {
String[] p = Arrays.copyOf(params, params.length);
Arrays.sort(p);
return join(p, "&");
}
private static String join(String[] array, String separator) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < array.length; i++) {
if (i > 0)
b.append(separator);
b.append(array[i]);
}
return b.toString();
}
//generating nonce value
private static String nonce() {
Random r = new Random();
StringBuilder n = new StringBuilder();
for (int i = 0; i < r.nextInt(8) + 2; i++)
n.append(r.nextInt(26) + 'a');
return n.toString();
}
//timestamp
Long tsLong = System.currentTimeMillis() / 1000;
int ts = Integer.parseInt(tsLong.toString());
private static String[] generateOauthParams(int page) {
return new String[]{
"oauth_consumer_key=" + APP_KEY,
"oauth_signature_method=HMAC-SHA1",
"oauth_timestamp=" +
Long.valueOf(System.currentTimeMillis() * 2).toString(),
"oauth_nonce=" + nonce(),
"oauth_version=1.0",
"format=json"};
}
private static String signature(String[] params) {
String[] p = {RecipeActivity.APP_METHOD, Uri.encode(RecipeActivity.APP_URL), Uri.encode(paramify(params))};
String s = join(p, "&");
SecretKey sk = new SecretKeySpec(APP_SECRET.getBytes(), HMAC_SHA1_ALGORITHM);
try {
Mac m = Mac.getInstance(HMAC_SHA1_ALGORITHM);
m.init(sk);
haang = Uri.encode(new String(Base64.encode(m.doFinal(s.getBytes()), Base64.DEFAULT)).trim());
return haang;
} catch (java.security.NoSuchAlgorithmException | java.security.InvalidKeyException e) {
Log.w("FatSecret_TEST FAIL", e.getMessage());
return null;
}
}
//signature method
//is is never used
public JSONObject searchRecipes(String searchRecipes, int page) {
List<String> params = new ArrayList<>(Arrays.asList(generateOauthParams(page)));
String[] template = new String[1];
params.add("method=recipes.search");
params.add("search_expression=" + Uri.encode(searchRecipes));
params.add("oauth_signature=" + signature(params.toArray(template)));
JSONObject foods = null;
try {
URL url = new URL(APP_URL + "?" + paramify(params.toArray(template)));
URLConnection api = url.openConnection();
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(api.getInputStream()));
while ((line = reader.readLine()) != null) builder.append(line);
JSONObject food = new JSONObject(builder.toString()); // { first
foods = food.getJSONObject("recipes"); // { second
} catch (Exception exception) {
Log.e("Json error", exception.toString());
exception.printStackTrace();
}
return foods;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe);
System.out.println("haang"+haang);
final RequestQueue requestQueue = Volley.newRequestQueue(RecipeActivity.this);
StringRequest stringRequest=new StringRequest(Request.Method.GET, APP_URL, new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("success", response);
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("error",error.getMessage());
}
});
requestQueue.add(stringRequest);
}
}
But i am getting error. i am tring to get the data in Xml form.here is my logcat.I am new to this concept and have no idea what i am doing wrong.
<error xmlns="http://platform.fatsecret.com/api/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://platform.fatsecret.com/api/1.0/ http://platform.fatsecret.com/api/1.0/fatsecret.xsd">
<code>2</code>
<message>Missing required oauth parameter: oauth_signature_method</message>
</error>
why i am getting this error .please guide me.

Related

android sunshine app live data is not loaded on list when i press refresh button

hi i have been following android sunshine Udacity course but i got stuck at loading live data from internet i log and i see data but it is not loaded on listView thanks in advance.
package com.example.ali.ican;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new ForcastFragment())
.commit();
}
}
}
ForcastFragment
/**
* A placeholder fragment containing a simple view.
*/
public class ForcastFragment extends android.support.v4.app.Fragment {
private static ArrayAdapter<String> ForcastIncoming;
public ForcastFragment() {
}
//---------------------------------------------------------
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new FetchWeatherTask().execute("London");
}
#Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.forcastfragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_refresh) {
FetchWeatherTask fetchWeatherTask = new FetchWeatherTask();
fetchWeatherTask.execute("119505");
Log.v("Action_refresh","works");
return true;
}
return super.onOptionsItemSelected(item);
}
//---------------------------------------------------------
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// api.openweathermap.org/data/2.5/forecast?q=Qazvin,Iran&mode=Json
// api.openweathermap.org/data/2.5/forecast/daily?q=Qazvin,Iran&mode=Json&units=metric&cnt=7
String [] wheather ={
"Today - sunny 88/66",
"Tommorow - foggy 65/66",
"Sunday - windy 55/63",
"Monday - cloudy 89/66"
};
List<String> WeekForecast =new ArrayList<String>(
Arrays.asList(wheather)
);
ForcastIncoming =
new ArrayAdapter<String>
(getActivity()
,R.layout.list_item_forcast,
R.id._list_item_forecast_textView,
WeekForecast);
ListView firstlist =(ListView) rootView.findViewById(R.id.list_view_foreccast);
firstlist.setAdapter(ForcastIncoming);
return rootView;
}
public class FetchWeatherTask extends AsyncTask<String ,Void, String[]>{
private final String LOG_TAG =FetchWeatherTask.class.getCanonicalName();
#Override
protected String[] doInBackground(String... params) {
Log.v("CityID",""+params);
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
int numDays =7;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
// final String FORCAST_BASE_URL ="http://api.openweathermap.org/data/2.5/forecast?id=119505&APPID=2a1ca9cdf8fa6bece6558112664c02ab";
final String FORCAST_BASE_URL ="http://api.openweathermap.org/data/2.5/forecast?id=119505&APPID=2a1ca9cdf8fa6bece6558112664c02ab";
final String QUERY_PARAM ="id";
final String QUERY_AAPID = "APPID";
final String APPID = "2a1ca9cdf8fa6bece6558112664c02ab";
final String QUERY_CNT = "cnt";
Uri uriBuilder = Uri.parse(FORCAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM,params[0])
.appendQueryParameter(QUERY_AAPID,APPID)
.appendQueryParameter(QUERY_CNT,Integer.toString(numDays))
.build();
// URL url = new URL("http://api.openweathermap.org/data/2.5/forecast?id=119505&APPID=2a1ca9cdf8fa6bece6558112664c02ab");
URL url = new URL(uriBuilder.toString());
Log.v("Uri_builder",""+uriBuilder);
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
// urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
// urlConnection.setRequestProperty("Accept","*/*");
// urlConnection.setRequestProperty("API_KEY", "2a1ca9cdf8fa6bece6558112664c02ab");
// urlConnection.setDoInput(true);
// urlConnection.setDoOutput(false);
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
Log.e("inputstreamshouting","yesssssssssnullllllllll");
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
Log.v("MAhdi","forcastJsonStr:" +forecastJsonStr);
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
try {
return getWeatherDataFromJson(forecastJsonStr,numDays);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] res) {
super.onPostExecute(res);
Log.v("From_onPost",""+res);
if (res !=null)
{
ForcastIncoming.clear();
for(String dayForcastTR :res){
ForcastIncoming.add(dayForcastTR);
}
}
ForcastIncoming.notifyDataSetChanged();
}
/* The date/time conversion code is going to be moved outside the asynctask later,
* so for convenience we're breaking it out into its own method now.
*/
private String getReadableDateString(long time){
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
Date date = new Date(time * 1000);
SimpleDateFormat format = new SimpleDateFormat("E, MMM d");
return format.format(date).toString();
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
Log.v("Testing_arg","this is the ::"+ forecastJsonStr);
// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "temp_max";
final String OWM_MIN = "temp_min";
final String OWM_DATETIME = "dt";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
String[] resultStrs = new String[numDays];
Log.v("here_weatherArray","works ::"+ weatherArray);
for(int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
Log.v("here_dayForecast","works ::"+dayForecast);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read "1400356800" as
// "this saturday".
long dateTime = dayForecast.getLong(OWM_DATETIME);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1 element long.
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
Log.v("herewat","worksk ::" + weatherObject);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_DESCRIPTION);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
Log.v("high","temperatureObject ::"+high);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
Log.v("_resultStrs","works ::"+resultStrs);
// Log.v("resultStrs[i]","this is the ::"+ resultStrs[i]);
// for(int ii=0;ii<resultStrs.length;i++){
//
// Log.v("_Parsing", "Forcast entry: " + resultStrs[ii]);
//
//
// }
return resultStrs;
}
return resultStrs;
}
}
}
i hope someone can help me again thanks in advance
Layout Structor
Make your List<String> WeekForecast as global and add new items in onPostExecute to it as in
#Override
protected void onPostExecute(String[] res) {
super.onPostExecute(res);
Log.v("From_onPost",""+res);
if (res !=null)
{
WeekForecast.clear();
WeekForecast.addAll(Arrays.asList(res));
ForcastIncoming.notifyDataSetChanged();
}
}

How to solve Caused by: java.lang.ArrayIndexOutOfBoundsException: length=18; index=18 in android?

I am developing an app, In this, I want to save users personal details onbutton click, But when I click on submit button it shows the error i.e Caused by java.lang.ArrayIndexOutOfBoundsException: length=18; index=18. How do I solve this? Please suggest me. Following is my code how do I solve this?.
//code
public class MyPersonalDetailsActivity1 extends AppCompatActivity {
RadioGroup rgGender, rgDopinion, rgYca, rgPye;
Button btnSave, btnBdate;
EditText edFname, edLname, edEmail, edPass, edAddress, edCountry, edState, edBdate, edCity, edMob, edHeight, edWeight, edQualification, edOccupation;
RadioButton rbYes, rbNo, rbFit, rbUnfit, rbYesa, rbNota, rbMale, rbFemale;
RadioButton rbGender, rbPye, rbDopinion, rbYca;
Toolbar toolbar;
TextView user_id, responsetypes;
Calendar myCalendar;
private boolean isLoggedIn = false;
SessionManagement session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_personal_details);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TextView toolbarTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbarTitle.setText("My Personal Details");
toolbar.setTitleMarginBottom(50);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
user_id=(TextView)findViewById(R.id.user_id);
edFname= (EditText)findViewById(R.id.ed_fname);
edEmail= (EditText)findViewById(R.id.ed_email);
edPass= (EditText)findViewById(R.id.ed_passowrd);
edMob= (EditText)findViewById(R.id.ed_mobile);
edBdate= (EditText)findViewById(R.id.ed_dob);
edAddress= (EditText)findViewById(R.id.ed_address);
edCountry= (EditText)findViewById(R.id.ed_country);
edState= (EditText)findViewById(R.id.ed_state);
edCity= (EditText)findViewById(R.id.ed_city);
edHeight= (EditText)findViewById(R.id.ed_height);
edWeight= (EditText)findViewById(R.id.ed_weight);
edQualification= (EditText)findViewById(R.id.ed_qaulification);
edOccupation= (EditText)findViewById(R.id.ed_occupation);
rgGender= (RadioGroup)findViewById(R.id.rg_gender);
rgDopinion= (RadioGroup)findViewById(R.id.rg_drop);
rgPye= (RadioGroup)findViewById(R.id.rg_pye);
rgYca= (RadioGroup)findViewById(R.id.rg_yca);
SharedPreferences sharedPreferences = getSharedPreferences(SessionManagement.PREF_NAME, Context.MODE_PRIVATE);
isLoggedIn = sharedPreferences.getBoolean(SessionManagement.IS_LOGIN, false);
String email = sharedPreferences.getString(SessionManagement.KEY_EMAIL, "Not Available");
user_id.setText(email);
myCalendar = Calendar.getInstance();
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
edBdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(MyPersonalDetailsActivity1.this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
//btnBdate=(Button)findViewById(R.id.btn_bdate);
btnSave=(Button)findViewById(R.id.btn_save);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_save) {
if (checkValidation()) {
int selectedIdGender = rgGender.getCheckedRadioButtonId();
rbGender = (RadioButton) findViewById(selectedIdGender);
int selectedIdYca = rgYca.getCheckedRadioButtonId();
rbYca = (RadioButton) findViewById(selectedIdYca);
int selectedIdPye = rgPye.getCheckedRadioButtonId();
rbPye = (RadioButton) findViewById(selectedIdPye);
int selectedIdDrop = rgDopinion.getCheckedRadioButtonId();
rbDopinion = (RadioButton) findViewById(selectedIdDrop);
String firstname1 = edFname.getText().toString();
String lastname = null;
String emailid = edEmail.getText().toString();
String password = edPass.getText().toString();
String address1 = edAddress.getText().toString();
String country = edCountry.getText().toString();
String state = edState.getText().toString();
String city = edCity.getText().toString();
String contactno = edMob.getText().toString();
String sex = rbGender.getText().toString();
String height = edHeight.getText().toString();
String weight = edWeight.getText().toString();
String qualification1 = edQualification.getText().toString();
String occupation1 = edOccupation.getText().toString();
String pye = rbPye.getText().toString();
String dopinion = rbDopinion.getText().toString();
String attendcourse = rbYca.getText().toString();
String birthdate = edBdate.getText().toString();
int userID = 12973;
String zipcode = null;
try {
String firstname = URLEncoder.encode(firstname1, "utf-8");
String address = URLEncoder.encode(address1, "utf-8");
String qualification = URLEncoder.encode(qualification1, "utf-8");
String occupation = URLEncoder.encode(occupation1, "utf-8");
System.out.println("Givennames is :" + firstname + " Given password is :" + password + "Gender:" + sex);
connectWithHttpGet(firstname, lastname, emailid, password, birthdate, zipcode,
sex, address, country, state, city, contactno,
height, weight, qualification, occupation, pye,
dopinion, attendcourse, userID);
if (isLoggedIn) {
//We will start the Profile Activity
Intent intent = new Intent(MyPersonalDetailsActivity1.this, MenuActivity.class);
startActivity(intent);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// Toast.makeText(MyPersonalDetailsActivity.this, "Please Fill the fields", Toast.LENGTH_LONG).show();
}
}
}
});
}
private void connectWithHttpGet(String firstname, String lastname, String emailid, String password, String birthdate,String zipcode,
String sex, String address, String country, String state, String city, String contactno,
String height, String weight, String qualification, String occupation, String pye,
String dopinion, String attendcourse, int userID) {
class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// As you can see, doInBackground has taken an Array of Strings as the argument
//We need to specifically get the givenUsername and givenPassword
String paramFname = params[0];
String paramLname = params[1];
String paramEmail = params[2];
String paramPassword = params[3];
String paramAddress = params[4];
String paramCountry = params[5];
String paramBirthdate = params[6];
String paramZip = params[7];
String paramState = params[8];
String paramCity = params[9];
String paramPhone = params[10];
String paramSex = params[11];
String paramHeight = params[12];
String paramWeight = params[13];
String paramQualifn = params[14];
String paramDopenion = params[15];
String paramPye = params[16];
String paramOccupatn = params[17];
String paramYca = params[18];
String paramUserid = params[19]; //HERE GIVES AN ERROR
System.out.println("userID" + paramFname + " email is :" + paramEmail+" gender is :" + paramSex);
// Create an intermediate to connect with the Internet
HttpClient httpClient = new DefaultHttpClient();
// Sending a GET request to the web page that we want
// Because of we are sending a GET request, we have to pass the values through the URL
HttpGet httpGet = new HttpGet("http://www.example.com/ypAndroid/api/SavePersonalDetails?firstname="+paramFname+"&lastname="+null+
"&emailid="+paramEmail+"&password="+paramPassword+
"&address1="+paramAddress+"&Country="+paramCountry+"&birthdate="+paramBirthdate+"&zipcode="+null+"&state="+paramState+
"&city="+paramCity+"&phonenumber="+paramPhone+"&sex="+paramSex+"&heightincms="+paramHeight+"&weightinkgs="+paramWeight+
"&qualification="+paramQualifn+"&doctorsopinion="+paramDopenion+"&PreviousYogaExperience="+paramPye+"&business="+paramOccupatn+
"&attendcourse="+paramYca+"&userid="+12973);
try {
// execute(); executes a request using the default context.
// Then we assign the execution result to HttpResponse
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("httpResponse// getEntity() ; obtains the message entity of this response");
// getContent() ; creates a new InputStream object of the entity.
// Now we need a readable source to read the byte stream that comes as the httpResponse
InputStream inputStream = httpResponse.getEntity().getContent();
// We have a byte stream. Next step is to convert it to a Character stream
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
// Then we have to wraps the existing reader (InputStreamReader) and buffer the input
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// InputStreamReader contains a buffer of bytes read from the source stream and converts these into characters as needed.
//The buffer size is 8K
//Therefore we need a mechanism to append the separately coming chunks in to one String element
// We have to use a class that can handle modifiable sequence of characters for use in creating String
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
// There may be so many buffered chunks. We have to go through each and every chunk of characters
//and assign a each chunk to bufferedStrChunk String variable
//and append that value one by one to the stringBuilder
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
// Now we have the whole response as a String value.
//We return that value then the onPostExecute() can handle the content
System.out.println("Returninge of doInBackground :" + stringBuilder.toString());
// If the Username and Password match, it will return "working" as response
// If the Username or Password wrong, it will return "invalid" as response
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("Exceptionrates caz of httpResponse :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Secondption generates caz of httpResponse :" + ioe);
ioe.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("httpResponse :" + result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray login = jsonObject.getJSONArray("savepersonaldetails");
JSONObject jsonObject1 = login.getJSONObject(0);
// edited second, you response was responsetype, but I parsed was responsetypes,so you can have a look.
String responsetypes = jsonObject1.optString("responsetype");
String message = jsonObject1.getString("message");
if (TextUtils.equals(responsetypes, "success")) {
Toast.makeText(getApplicationContext(), message , Toast.LENGTH_LONG).show();
} else if (TextUtils.equals(responsetypes, "failure")) {
Toast.makeText(getApplicationContext(), message , Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
// Initialize the AsyncTask class
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
// Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
// We are passing the connectWithHttpGet() method arguments to that
httpGetAsyncTask.execute(firstname,lastname,emailid,password,birthdate,zipcode,sex,address,country,city,contactno,
height,weight,qualification,occupation,pye,dopinion,attendcourse, String.valueOf(userID));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// action with ID action_refresh was selected
case android.R.id.home:
Intent i8= new Intent(this, MenuActivity.class);
i8.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i8);
finish();
return true;
default:
break;
}
return true;
}
private boolean checkValidation() {
boolean ret = true;
if (!Validation.hasText(edFname)) ret = false;
if (!Validation.hasText(edPass)) ret = false;
if (!Validation.isEmailAddress(edEmail, true)) ret = false;
if (!Validation.isBirthDate(edBdate, true)) ret = false;
if (!Validation.hasText(edAddress)) ret = false;
if (!Validation.hasText(edCountry)) ret = false;
if (!Validation.hasText(edState)) ret = false;
if (!Validation.hasText(edCity)) ret = false;
if (!Validation.isPhoneNumber(edMob, true)) ret = false;
if (!Validation.hasText(edHeight)) ret = false;
if (!Validation.hasText(edWeight)) ret = false;
if (!Validation.hasText(edQualification)) ret = false;
if (!Validation.hasText(edOccupation)) ret = false;
return ret;
}
private void updateLabel() {
String myFormat = "yyyy/MM/dd"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
edBdate.setText(sdf.format(myCalendar.getTime()));
}
}
Your httpGetAsyncTask.execute call only passes 18 parameters whereas you are trying to get the 19th parameter in String paramUserid = params[19];. Hence the error. Check your execute call and pass more params.
PS : this is not an ideal way to pass data though. No method call should have 19 parameters. Create a model class of type User containing these 19 fields, and set the values in that model class and then pass it.

Android ListView Updated by AsyncTaskLoader

I'm populating a ListView from DB. The recordset from the DB contains the Zipcode which is then transformed into City and State using google map api and then set to Listview Item.
I need to be able to set the value that is being returned from the background class in Listview. Any guidance would be very much appreciated. Thanks in advance.
for (int i = 0; i < zipcodes.getLength(); i++) {
GetCityStateInfoFromPostalCode getCityStateInfoFromPostalCode = new GetCityStateInfoFromPostalCode(getActivity(), "110001", "ta");
String mCityState = getCityStateInfoFromPostalCode.getCityState();
}
Here's Background Class that fetches the info from Google maps api
public class GetCityStateInfoFromPostalCode extends AsyncTaskLoader<String> {
private String URL;
private String mState = "";
private String mCity = "";
private Context mContext;
public String getCityState() {
return mCityState;
}
private String mCityState = "";
public GetCityStateInfoFromPostalCode(Context context, String postalCode, String language) {
super(context);
this.mContext = context;
URL = "http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:" + postalCode + "&language=" + language;
// Kick start the load process
forceLoad();
}
public String loadInBackground() {
JSONObject jsonObject;
JSONArray jsonRootArray;
JSONArray jsonAdressArray;
JSONObject addressComponentCityObject;
JSONObject addressComponentStateObject;
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
httpGet.addHeader("content-type", "application/json");
try {
HttpResponse resp = client.execute(httpGet);
String json = EntityUtils.toString(resp.getEntity(), "UTF-8");
jsonObject = new JSONObject(json);
addressComponentCityObject = new JSONObject();
addressComponentStateObject = new JSONObject();
jsonRootArray = jsonObject.getJSONArray("results");
//This points to "0"
JSONObject rootJson = jsonRootArray.getJSONObject(0);
//This points to address components
jsonAdressArray = rootJson.getJSONArray("address_components");
//This points to Object 1 (Second object of the jsonAddressArray)
addressComponentCityObject = jsonAdressArray.getJSONObject(1);
mCity = addressComponentCityObject.getString("long_name");
addressComponentStateObject = jsonAdressArray.getJSONObject(3);
mState = addressComponentStateObject.getString("long_name");
} catch (Throwable t) {
// Handle error here
t.printStackTrace();
}
this.mCityState = mCity + ", " + mState;
return mCityState;
}
}
with AsyncTask you can generate and override the methods below :
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
I hope this will help you :)

how to add OnScrollListener in my below code

It's been a while since I have been using android. can you please tell me how to add OnScrollListener in this code ? Everytime I scroll down I want to fetch 5 more images.
This is the Asyncatask its working correct, but I need fetch 5 image everytime I scroll down(load more).
public class RecyclerOkHttpHandler extends AsyncTask<String, Void, String> {
private Context mContext;
private MyInterface mListener;
public String category;
public String basestart;
public String limitend;
public RecyclerOkHttpHandler(Context context, MyInterface mListener, String categ, String base, String limit){
mContext = context;
this.mListener = mListener;
category=categ;
basestart=base;
limitend=limit;
}
public interface MyInterface {
public void myMethod(ArrayList result);
}
private final String Fetch_URL = "http://justedhak.com/old-files/Recyclerview_data.php";
// ArrayList<Listitem> Listitem;
ArrayList<CategoryList> Listitem;
int resulta;
OkHttpClient httpClient = new OkHttpClient();
ListView list;
String myJSON;
JSONArray peoples = null;
InputStream inputStream = null;
#Override
protected String doInBackground(String... params) {
Log.d("okhttp Fetch_URL", Fetch_URL);
RequestBody formBody = new FormEncodingBuilder()
.add("category", category)
.add("base", basestart)
.add("limit", limitend)
.build();
Request request = new Request.Builder()
.url(Fetch_URL)
.post(formBody)
.build();
String result = null;
try {
Response response = httpClient.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
inputStream = response.body().byteStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
resulta = 1; //"Success
// return response.body().bytes();
} catch (Exception e) {
Toast.makeText(mContext, "Connection failed, check your connection",
Toast.LENGTH_LONG).show();
e.printStackTrace(); }
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
if( resulta ==1){
myJSON=result;
Log.e("result",result);
showList();
}
else{
Log.e("d","there is an error on postexecute in okhhttphandler.java");
}
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray("result");
System.out.println("Length:"+peoples.length());
int J_length=peoples.length()-1;
//JSONObject maxj = peoples.getJSONObject(peoples.length() - 1);
// max of arrray
jsonObj= peoples.getJSONObject(J_length);
String j_id= jsonObj.getString("id");
int _id = Integer.parseInt(j_id);
System.out.println(j_id);
//max of
DatabaseHandler db = new DatabaseHandler(mContext);
String db_id="";
db_id = db.getmax();
if (db_id== null)
{
db_id="0";
}
int d_id = Integer.parseInt(db_id);
Log.e("db_id", db_id);
Log.e("j_id",j_id);
// if (_id < d_id) {
System.out.println("Getting json result ");
Listitem = new ArrayList<CategoryList>();
for (int i = 0; i < peoples.length(); i++) {
JSONObject c = peoples.getJSONObject(i);
String id = c.getString("id");
String url = c.getString("url");
Listitem.add(new CategoryList(id, url));
}
if (mListener != null)
mListener.myMethod(Listitem);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is the when I set the adapter
private String base = "0";
private String limit = "5";
final RecyclerOkHttpHandler handler = new RecyclerOkHttpHandler( this, new RecyclerOkHttpHandler.MyInterface() {
#Override
public void myMethod(ArrayList result) {
mAdapter_first = new MyAdapter(result,SearchActivity.this);
mAdapter_first.notifyDataSetChanged();
mRecyclerView_first.setAdapter(mAdapter_first);
}
},"girls jokes",base,limit);
try {
handler.execute().get();
} catch (Exception e) {
Log.d("SearchActivity error", "error in mRecyclerView_first");
e.printStackTrace();
}
For the first load, call your RecyclerOkHttpHandler AsyncTaskto get your first 5 items.
Now, for any further load, all you have to do is to check if the listView is scrolled to its bottom and you can refer to this link Find out if ListView is scrolled to the bottom? to know how to deal with it.
So, each time you detect that the user has scrolled the listview to the bottom, it's time to call the RecyclerOkHttpHandler AsynTask to get the 5 new images.
PS: You need to save the limit you have reached in each load, so that in the next load, you start loading from that limit.
Hope this helps :)

Using the MyWeather2 web service in android

I am new to android , and I need an example to use / consume the following Web service in an application developed on android studio :
http://www.myweather2.com/developer/weather.ashx?uac=ENHRNh-psb&uref=53694bca-82a0-4de3-8a9b-70e4fe0b3e94
I would be very useful to be very specific.
Use JSON API instead of XML, that will make your task easier.
public class QueryBuilder {
//This is your unique key as I can see in the URL
private static final String KEY = "ENHRNh-psb";
// Take output as JSON instead of XML
private static final String OUTPUT = "json";
private static final String BASE_URL = "http://www.myweather2.com/developer/weather.ashx?";
private String query;
public QueryBuilder() {
//build the base query with key and output
this.query = BASE_URL + "uac=" + KEY + "&output=" + OUTPUT;
}
//Example of methods which you can add according to your requirement
public QueryBuilder setLocalityFilter(String locality) {
this.query = this.query + "&filters={\"locality\":{\"$eq\":\"" + locality + "\"}}";
return this;
}
public String build() {
return this.query;
}
}
Example of JSON parser class
public class JsonParser {
public static ArrayList<Restaurant> parseHTTPResponse(String responseString) {
ArrayList<Restaurant> restaurantArrayList= new ArrayList<>();
try {
JSONObject baseObject = new JSONObject(responseString);
JSONObject responseObject = baseObject.getJSONObject("response");
JSONArray restaurantArray = responseObject.getJSONArray("data");
for (int i =0; i<restaurantArray.length();i++) {
Restaurant restaurant = new Restaurant();
JSONObject restaurantObject = restaurantArray.getJSONObject(i);
restaurant.setName(restaurantObject.getString("name"));
restaurant.setAddress(restaurantObject.getString("address"));
restaurant.setRating(restaurantObject.getDouble("rating"));
// Check if the restaurant has its cuisine listed, if yes add it to type
if(restaurantObject.has("cuisine")) {
JSONArray cuisineArray = restaurantObject.getJSONArray("cuisine");
StringBuilder stringBuilder = new StringBuilder();
for (int j = 0; j < cuisineArray.length(); j++) {
String cuisine = cuisineArray.getString(j);
stringBuilder.append(cuisine);
stringBuilder.append(" ,");
}
restaurant.setType(stringBuilder.toString());
}
restaurantArrayList.add(restaurant);
}
}
catch (JSONException ex) {
ex.printStackTrace();
}
return restaurantArrayList;
}
}
Build the query like this
String httpQuery = new QueryBuilder().setLocalityFilter(query).build();
try {
HttpRequest request = HttpRequest.get(httpQuery);
if (request.ok()) {
String response = request.body();
restaurantArrayList = JsonParser.parseHTTPResponse(response);
}
return restaurantArrayList;
} catch (HttpRequest.HttpRequestException exception) {
return null;
}

Categories

Resources