Recently I developed one app. In this, The values are retrieved from the MySQL data base into the spinner. The problem is that it crashes when internet is not present. My intention is, if the internet is not present show default values. Otherwise if the internet is available show the values from MySQL database.
public class MilkProduction extends AppCompatActivity implements Spinner.OnItemSelectedListener{
private EditText quantity;
private Button submit, cancel;
private TextView date_time;
Calendar calander;
SimpleDateFormat simpleDateFormat;
String time;
private AutoCompleteTextView animal_id;
private List<Animal> fruits ;
Boolean isInternetPresent = false;
private ConnectionDetector cd;
private Spinner spinner1;
private String shift_id;
private String product;
String shiftid="",intime="",outtime="";
//JSON Array
private JSONArray result;
//An ArrayList for Spinner Items
private ArrayList<String> students;
private Animal item ;
private Animal animal=new Animal();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
setContentView(R.layout.milk_production);
animal_id = (AutoCompleteTextView) findViewById(R.id.edt_animal_id);
quantity = (EditText) findViewById(R.id.edt_milkproduction_quan);
date_time = (TextView) findViewById(R.id.txt_timt_date_year);
submit = (Button) findViewById(R.id.btn_prodc_submit);
calander = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
time = simpleDateFormat.format(calander.getTime());
date_time.setText(time);
date_time.setTextSize(15);
students = new ArrayList<String>();
spinner1 = (Spinner) findViewById(R.id.spinner);
spinner1.setOnItemSelectedListener(this);
cd = new ConnectionDetector(getApplicationContext());
//Calling the method that will fetch data
proautocomplete();
prodropdown();
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
insertUser();
}
else{
showAlertDialog(MilkProduction.this, "Internet not available",
"Internet is not available in this device", false);
}
}
});
}
private void prodropdown() {
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(Config.ROOT_URL) //Setting the Root URL
.build(); //Finally building the adapter
//Creating object for our interface
AnimalAPI api = adapter.create(AnimalAPI.class);
api.insertUser1( new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
String detailsString = Others.getStringFromRetrofitResponse(response);
try {
//Parsing the fetched Json String to JSON Object
JSONObject j = new JSONObject(detailsString);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void failure(RetrofitError error) {
}
});
}
private void getStudents(JSONArray j) {
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner1.setAdapter(new ArrayAdapter<String>(MilkProduction.this, android.R.layout.simple_spinner_dropdown_item, students));
}
//Method to get student name of a particular position
private String getShiftid(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
// name = json.getString(Config.TAG_NAME);
name = animal.setShiftid(json.getString(Config.TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
//Doing the same with this method as we did with getName()
private String getIntime(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
// course = json.getString(Config.TAG_COURSE);
course= animal.setIntime(json.getString(Config.TAG_COURSE));
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}
//Doing the same with this method as we did with getName()
private String getOuttime(int position){
String session="";
try {
JSONObject json = result.getJSONObject(position);
// session = json.getString(Config.TAG_SESSION);
session= animal.setOuttime(json.getString(Config.TAG_SESSION));
} catch (JSONException e) {
e.printStackTrace();
}
return session;
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
String spin = parent.getItemAtPosition(position).toString();
//Setting the values to textviews for a selected item
shiftid=(getShiftid(position));
intime=(getIntime(position));
outtime=(getOuttime(position));
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
shiftid="";
intime="";
outtime="";
}
private void insertUser() {
//While the app fetched data we are displaying a progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Loading","Please wait...",false,false);
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(Config.ROOT_URL) //Setting the Root URL
.build(); //Finally building the adapter
//Creating object for our interface
AnimalAPI api = adapter.create(AnimalAPI.class);
api.insertUser(
animal_id.getText().toString(),
quantity.getText().toString(),
date_time.getText().toString(),
spinner1.getSelectedItem().toString(),
" ",
shiftid,
intime,
outtime,
new Callback<Response>() {
#Override
public void success(Response result, Response response) {
//On success we will read the server's output using bufferedreader
loading.dismiss();
//Creating a bufferedreader object
BufferedReader reader = null;
//An string to store output from the server
String output = "";
try {
reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
//Reading the output in the string
output = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
//Displaying the output as a toast
Toast.makeText(MilkProduction.this, output, Toast.LENGTH_LONG).show();
}
#Override
public void failure(RetrofitError error) {
//If any error occured displaying the error as toast
loading.dismiss();
Toast.makeText(MilkProduction.this, error.toString(), Toast.LENGTH_LONG).show();
}
}
);
}
}
Layout:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/mm"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="#dimen/dairy_layout_height"
android:orientation="vertical"
android:layout_gravity="center_horizontal"
android:gravity="center_vertical|center_horizontal"
android:layout_marginTop="25dp"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:background="#drawable/corner3"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="13dp"
android:layout_gravity="center"
>
<TextView
android:id="#+id/heder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Milk Production"
android:layout_gravity="center"
android:gravity="center"
android:layout_margin="5dp"
android:textSize="25sp"
android:textColor="#color/textcolour"
/>
<View
android:layout_width="250dp"
android:layout_height="2dip"
android:background="#023e64"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="13dp"
android:layout_gravity="left"
android:layout_weight="1"
>
<TextView
android:id="#+id/txt_animal_shfit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shift : "
android:textSize="20sp"
android:textColor="#color/textcolour"
android:layout_weight="0.40"
android:gravity="left"
android:layout_marginTop="12dp"
/>
<Spinner
android:layout_width="160dp"
android:layout_height="50dp"
android:id="#+id/spinner"
android:layout_gravity="center_horizontal"
android:spinnerMode="dialog"
android:prompt="#string/shift_prompt"
android:background="#android:drawable/btn_dropdown"
android:entries="#array/android_dropdown_arrays1"
style="#android:style/Widget.Holo.Light.Spinner"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="13dp"
android:layout_gravity="left"
android:layout_weight="1"
>
<TextView
android:id="#+id/txt_animal_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Animal : "
android:textSize="20sp"
android:textColor="#color/textcolour"
android:layout_weight="0.40"
android:gravity="left"
/>
<AutoCompleteTextView
android:id="#+id/edt_animal_id"
android:layout_width="160dp"
android:layout_height="50dp"
android:background="#drawable/corner1"
android:layout_weight="0.60"
android:layout_alignParentLeft="true"
android:ems="10"
android:text="">
</AutoCompleteTextView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="13dp"
android:layout_gravity="left"
android:layout_weight="1"
>
<TextView
android:id="#+id/txt_milk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Quantity : "
android:textSize="20sp"
android:textColor="#color/textcolour"
android:layout_weight="0.40"
android:gravity="left"
/>
<EditText
android:id="#+id/edt_milkproduction_quan"
android:layout_width="121dp"
android:layout_height="50dp"
android:background="#drawable/corner1"
android:layout_weight="0.60"
android:inputType="number"
android:ems="10"
/>
<TextView
android:id="#+id/txt_milk_quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Lts."
android:textSize="20sp"
android:textColor="#color/textcolour"
android:layout_weight="0.40"
android:gravity="right"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="13dp"
android:layout_gravity="left"
>
<TextView
android:id="#+id/btn_prodc_submit"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Submit"
android:textSize="#dimen/button_sub_txt_size"
android:layout_margin="#dimen/button_layout_margin"
android:background="#drawable/btnbackground"
android:textColor="#color/textcolour"
/>
</LinearLayout>
</LinearLayout>
</ScrollView>
I think should try something like that to show the default values if no internet, else get the values of the sql
if(cd.isConnectingToInternet()){
prodropdown();
}else{
//Setting adapter to show the items in the spinner
List<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("default value 1");
spinnerArray.add("default value 2");
spinnerArray.add("default value 3");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
}
Related
I have one problem with my RecyclerView - it doesn't update on the main screen after pressing on the button. It can only appear after close/open soft keeboard. I looked a lot of solutions overe here but nothing helped me. I have just a simple app which sends a request "String" to server and gets one JSON Object and next inserts it on RecyclerView. But the data in RecyclerView don't apear immediately. I'm in deadlock. Help me.
Code in the activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/sky"
tools:context=".MainActivity">
<EditText
android:id="#+id/editTextRequestCity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/write_name_of_city_or_index"
android:inputType="textPersonName"
android:maxLength="30"
android:minHeight="48dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toTopOf="#+id/recyclerViewListForecast"
app:layout_constraintEnd_toStartOf="#+id/buttonShowWeather"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/buttonShowWeather"
android:layout_width="54dp"
android:layout_height="48dp"
android:background="#drawable/search_city"
android:onClick="onClickShowWeather"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toTopOf="#+id/recyclerViewListForecast"
app:layout_constraintStart_toEndOf="#+id/editTextRequestCity"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewListForecast"
app:layoutManager="LinearLayoutManager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editTextRequestCity"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Code in the weather_item.xml:
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/cardViewItem"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="1dp"
app:cardCornerRadius="1dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textViewDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:background="#00FFFFFF"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewFallout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewDegree"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewPressure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewHumidity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewSpeedWind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewGustWind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textColor="#color/black"
android:textSize="15sp" />
<TextView
android:id="#+id/textViewDirectionWind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center"
android:textSize="15sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
Code in WeatherItem:
package com.example.forecast;
public class WeatherItem {
private String date;
private String time;
private String fallout;
private String degree;
private String pressure;
private String humidity;
private String speedWind;
private String gustWind;
private String directionWind;
public WeatherItem(String date, String time, String fallout, String degree, String pressure, String humidity, String speedWind, String gustWind, String directionWind) {
this.date = date;
this.time = time;
this.fallout = fallout;
this.degree = degree;
this.pressure = pressure;
this.humidity = humidity;
this.speedWind = speedWind;
this.gustWind = gustWind;
this.directionWind = directionWind;
}
public String getDate() {
return date;
}
public String getTime() {
return time;
}
public String getFallout() {
return fallout;
}
public String getDegree() {
return degree;
}
public String getPressure() {
return pressure;
}
public String getHumidity() {
return humidity;
}
public String getSpeedWind() {
return speedWind;
}
public String getGustWind() {
return gustWind;
}
public String getDirectionWind() {
return directionWind;
}
}
Code in WeatherAdapter:
package com.example.forecast;
public class WeatherAdapter extends RecyclerView.Adapter<WeatherAdapter.WeatherViewHolder> {
public ArrayList<WeatherItem> weatherItems;
Context context;
public WeatherAdapter(Context context, ArrayList <WeatherItem> weatherItems) {
this.context = context;
this.weatherItems = weatherItems;
}
#NonNull
#Override
public WeatherViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.weather_item, parent, false);
return new WeatherViewHolder(view);
}
#Override
public void onBindViewHolder(final WeatherViewHolder holder, int position) {
WeatherItem weatherItem = weatherItems.get(position);
holder.textViewDate.setText(weatherItem.getDate());
holder.textViewTime.setText(weatherItem.getTime());
holder.textView.setText(weatherItem.getFallout());
holder.textViewDegree.setText(weatherItem.getDegree());
holder.textViewPressure.setText(weatherItem.getPressure());
holder.textViewHumidity.setText(weatherItem.getHumidity());
holder.textViewSpeedWind.setText(weatherItem.getSpeedWind());
holder.textViewGustWind.setText(weatherItem.getGustWind());
holder.textViewDirectionWind.setText(weatherItem.getDirectionWind());
}
#Override
public int getItemCount() {
return weatherItems.size();
}
static class WeatherViewHolder extends RecyclerView.ViewHolder {
private TextView textViewDate;
private TextView textViewTime;
private TextView textView;
private TextView textViewDegree;
private TextView textViewPressure;
private TextView textViewHumidity;
private TextView textViewSpeedWind;
private TextView textViewGustWind;
private TextView textViewDirectionWind;
public WeatherViewHolder(#NonNull View itemView) {
super(itemView);
textViewDate = itemView.findViewById(R.id.textViewDate);
textViewTime = itemView.findViewById(R.id.textViewTime);
textView = itemView.findViewById(R.id.textViewFallout);
textViewDegree = itemView.findViewById(R.id.textViewDegree);
textViewPressure = itemView.findViewById(R.id.textViewPressure);
textViewHumidity = itemView.findViewById(R.id.textViewHumidity);
textViewSpeedWind = itemView.findViewById(R.id.textViewSpeedWind);
textViewGustWind = itemView.findViewById(R.id.textViewGustWind);
textViewDirectionWind = itemView.findViewById(R.id.textViewDirectionWind);
}
}
}
And finaly my code in MainActivity:
public class MainActivity extends AppCompatActivity {
EditText editTextRequestCity;
private RecyclerView recyclerViewListForecast;
WeatherAdapter adapter;
private ArrayList<WeatherItem> weatherItems = new ArrayList<>();
private final String WEATHER_URL = "https://api.openweathermap.org/data/2.5/forecast?q=%s&lang=ru&units=metric&appid=ce288368c68807e060c17369bfbef3b3";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextRequestCity = findViewById(R.id.editTextRequestCity);
recyclerViewListForecast = findViewById(R.id.recyclerViewListForecast);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerViewListForecast.setLayoutManager(linearLayoutManager);
adapter = new WeatherAdapter(getApplicationContext(), weatherItems = new ArrayList<>());
recyclerViewListForecast.setAdapter(adapter);
}
public void onClickShowWeather(View view) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
weatherItems.clear();
adapter.notifyDataSetChanged();
String city = editTextRequestCity.getText().toString().trim();
String request = String.format(WEATHER_URL,city);
DownLoadWeatherTask task = new DownLoadWeatherTask();
task.execute(request);
}
private class DownLoadWeatherTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
URL url = null;
HttpURLConnection urlConnection = null;
StringBuilder result = new StringBuilder();
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
result.append(line);
line = reader.readLine();
}
return result.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
try {
JSONObject jsonObjectMain = new JSONObject(s);
JSONArray jsonArray = jsonObjectMain.getJSONArray("list");
for (int i = 0; i < jsonArray.length(); i++) {
ArrayList<WeatherItem> weatherItemDay = new ArrayList<>();
JSONObject jsonObjectDay = jsonArray.getJSONObject(i);
String dateTime = jsonObjectDay.getString("dt_txt");
String date = dateTime.substring(0, 10).trim();
String time = dateTime.substring(11, 16).trim();
String fallout = jsonObjectDay.getJSONArray("weather").getJSONObject(0).getString("description").trim();
String degree = String.format("" + jsonObjectDay.getJSONObject("main").getInt("temp")).trim();
String pressure = String.format("" + jsonObjectDay.getJSONObject("main").getInt("pressure")).trim();
String humidity = String.format("" + jsonObjectDay.getJSONObject("main").getInt("humidity")).trim();
String speedWind = String.format("" + jsonObjectDay.getJSONObject("wind").getInt("speed")).trim();
String gustWind = String.format("" + jsonObjectDay.getJSONObject("wind").getInt("gust")).trim();
String directionWind = String.format("" + jsonObjectDay.getJSONObject("wind").getInt("deg")).trim();
weatherItems.add(new WeatherItem(date, time, fallout, degree, pressure, humidity, speedWind, gustWind, directionWind));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
Call notifyDataSetChanged() when you add a new item to your list. Based on your code, this needs to happen in onPostExecute for you.
You are already calling notifyDataSetChanged() in the onClick but this is before the task has finished, therefore the item doesn't show because it hasn't been added to the list yet.
I have a project which shows list of blood donors using place search, i want to insert a call button in that list view for each user, i have no idea how to add it, Can you please help me with this? Screenshot 1: Screenshot 2: Each detail of the blood donor like name , blood group and phone are stored in each field in the server. "bld_phn" is the id of text view that shows phone number."phone" is the array string
code:
public class blood extends Activity {
AsyncHttpClient client;
JSONArray jarray;
JSONObject jobject;
RequestParams params;
ListView lv;
EditText enter;
Button done;
Button call;
ArrayList<String> place;
ArrayList<String>incharge;
ArrayList<String>email;
ArrayList<String>phone;
ArrayList<String>reg;
ArrayList<String>Bld;
String temp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.blood);
//prof=(EditText)findViewById(R.id.userProfile);
client = new AsyncHttpClient();
params = new RequestParams();
// submit=(Button)findViewById(R.id.submit);
lv = (ListView) findViewById(R.id.List_all_blood);
enter=(EditText)findViewById(R.id.enter_bld);
done=(Button)findViewById(R.id.enter_blood);
place = new ArrayList<String>();
incharge = new ArrayList<String>();
email = new ArrayList<String>();
phone = new ArrayList<String>();
reg = new ArrayList<String>();
Bld = new ArrayList<String>();
// final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl2);
// findViewById(R.id.rl1).setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v) {
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.hideSoftInputFromWindow(rl.getWindowToken(), 0);
//
// }
// });
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
place.clear();
incharge.clear();
email.clear();
phone.clear();
reg.clear();
String pl=enter.getText().toString();
params.put("place",pl);
client.get("http://srishti-systems.info/projects/accident/bloodsearch.php?", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String content) {
// TODO Auto-generated method stub
super.onSuccess(content);
System.out.println(content + "jjjjj");
try {
jobject = new JSONObject(content);
Log.e(content, "hgsfdh");
String s = jobject.optString("Result");
Log.e(content,"dsfds");
if(s.equals("success")){
// SharedPreferences pref=getApplicationContext().getSharedPreferences("pref",MODE_PRIVATE);
// temp=pref.getString("user","");
// String a = jobject.optString("PoliceDetails");
jarray =jobject.getJSONArray("BloodDoner");
for (int i = 0; i < jarray.length(); i++) {
JSONObject obj = jarray.getJSONObject(i);
String FN = obj.getString("firstname");
place.add("First Name :" + FN);
String LN = obj.getString("lastname");
incharge.add("Second Name :" + LN);
String mail = obj.getString("email");
email.add("Email :" + mail);
String ph = obj.getString("phone");
phone.add("Phone :" + ph);
String bd = obj.getString("bloodgrp");
Bld.add("BLood Group :" + bd);
}
}
else
Toast.makeText(getApplicationContext(),"No Donors Found",Toast.LENGTH_LONG).show();
adapter adpt = new adapter();
lv.setAdapter(adpt);
} catch (Exception e) {
}
}
});
}
});
}
public void hideKeyboard(View view) {
InputMethodManager imm =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
class adapter extends BaseAdapter {
LayoutInflater Inflater;
#Override
public int getCount() {
// TODO Auto-generated method stub
return place.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Inflater=(LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=Inflater.inflate(R.layout.blood_lst,null);
Viewholder holder=new adapter.Viewholder();
holder.pl=(TextView)convertView.findViewById(R.id.bld_name);
holder.pl.setText(place.get(position));
holder.in=(TextView)convertView.findViewById(R.id.bld_nm);
holder.in.setText(incharge.get(position));
holder.em=(TextView)convertView.findViewById(R.id.bld_em);
holder.em.setText(email.get(position));
holder.ph=(TextView)convertView.findViewById(R.id.bld_phn);
holder.ph.setText(phone.get(position));
holder.ph=(TextView)convertView.findViewById(R.id.bld_grp);
holder.ph.setText(Bld.get(position));
return convertView;
}
class Viewholder{
TextView pl;
TextView in;
TextView em;
TextView ph;
}
}
}
xml of the page :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rl2"
android:background="#9e9e9e">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/List_all_blood"
android:layout_below="#+id/enter_bld"
/>
<EditText
android:hint="enter place"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/enter_bld"
android:layout_weight="1"
android:layout_marginTop="49dp"
android:textColor="#000000"
android:textStyle="italic"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/enter_policebutton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:text="done"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:textColor="#FFFFFF"
android:background="#3F51B5"
android:layout_marginRight="34dp"
android:layout_marginEnd="34dp"
android:id="#+id/enter_blood"
style="#style/Widget.AppCompat.Button"
android:layout_alignBaseline="#+id/enter_bld"
android:layout_alignBottom="#+id/enter_bld"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/enter_blood"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="11dp"
android:text="Blood Doners" />
</RelativeLayout>
xml of the list :
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#9e9e9e">
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginTop="25dp"
android:textSize="15dp"
android:layout_marginLeft="30dp"
android:id="#+id/bld_name" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginLeft="30dp"
android:textSize="15dp"
android:textColor="#000000"
android:id="#+id/bld_nm"
android:layout_below="#+id/bld_name" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginTop="15dp"
android:textSize="15dp"
android:layout_marginLeft="30dp"
android:id="#+id/bld_em" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginTop="15dp"
android:textSize="15dp"
android:layout_marginLeft="30dp"
android:id="#+id/bld_phn" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginTop="15dp"
android:textSize="15dp"
android:layout_marginLeft="30dp"
android:id="#+id/bld_grp" />
</TableLayout>
For call button in listview you can add call button icon in listview's row file like below:-
<Button
android:id="#+id/buttonCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Call" />
Then in activity, you can write below code in on click of call button to call functionality in android:-
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("phone number"));
startActivity(callIntent);
phone number in above code is a string var in which you can add number which you want to call.
I hope it will help you.
I am developing an signup activity in android app. I want show the country telephone code(get the country from device). It may show the list of countries containing with flag, country telephone code, country name. I get the code of country code picker from https://github.com/mukeshsolanki/country-picker-android . It contain the complete code. I want to set the default country is in the phone.
TelephonyManager tm = (TelephonyManager)this.getSystemService(this.TELEPHONY_SERVICE);
String countryCodeValue = tm.getNetworkCountryIso();
System.out.println("country = "+country);
When i using this code i get the country code "in". But i want to display telephone code and flag, name. When i open the screen. I want to display it automatically.
My code is shown below
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/colorBackground"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_gravity="center_vertical"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="56dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<ImageView
android:background="#drawable/logo"
android:layout_gravity="center_horizontal"
android:layout_width="150dp"
android:layout_height="150dp" />
<Button
android:text="Country"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/buttonCountry" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:backgroundTint="#d11f08"
android:entries="#array/android_dropdown_arrays"
android:padding="5dp" />
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/editTextPhone"
android:layout_width="match_parent"
android:layout_height="44dp"
android:inputType="phone"
android:hint="Password"/>
</android.support.design.widget.TextInputLayout>
<android.support.v7.widget.AppCompatButton
android:id="#+id/buttonSubmit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:textColor="#color/colorAccent"
android:layout_marginTop="24dp"
android:layout_marginBottom="24dp"
android:padding="12dp"
android:text="Login"/>
</LinearLayout>
</ScrollView>
Main.Activity
public class MainActivity extends AppCompatActivity {
EditText editText;
Button button;
Button buttonCountry;
private Spinner spinner1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editTextPhone);
button = (Button) findViewById(R.id.buttonSubmit);
buttonCountry = (Button) findViewById(R.id.buttonCountry);
spinner1 = (Spinner) findViewById(R.id.spinner1);
TelephonyManager tm = (TelephonyManager)this.getSystemService(this.TELEPHONY_SERVICE);
String countryCodeValue = tm.getNetworkCountryIso();
System.out.println("country = "+countryCodeValue);
//String mPhoneNumber = tm.getLine1Number(); //not getting phone number
//System.out.println("phone no = "+mPhoneNumber);
buttonCountry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinner1.setOnItemSelectedListener(new ItemSelectedListener());
final CountryPicker picker = CountryPicker.newInstance("Select Country");
picker.show(getSupportFragmentManager(), "COUNTRY_PICKER");
picker.setListener(new CountryPickerListener() {
#Override
public void onSelectCountry(String name, String code, String dialCode, int flagDrawableResID) {
// Implement your code here
Log.d("LOGTAG", "output1 : name = "+name+" code = "+code+" dialcode = "+dialCode+" flag = "+flagDrawableResID);
picker.dismiss();
}
});
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public class ItemSelectedListener implements AdapterView.OnItemSelectedListener {
//get strings of first item
String firstItem = String.valueOf(spinner1.getSelectedItem());
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (firstItem.equals(String.valueOf(spinner1.getSelectedItem()))) {
// ToDo when first item is selected
} else {
Toast.makeText(parent.getContext(),
"You have selected : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG).show();
// Todo when item is selected by the user
}
}
#Override
public void onNothingSelected(AdapterView<?> arg) {
}
}
}
Reference : https://github.com/hbb20/CountryCodePickerProject
try to get country code using Lat, long
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addressList = geocoder.getFromLocation(
lati, longi, 1); // lati : Latitude ,longi : Longitude
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
code=addressList.get(0).getCountryCode();
System.out.println("code :: "+addressList.get(0).getCountryCode());
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
}
String locale = context.getResources().getConfiguration().locale.getCountry();
You can use this library
Click here
by then you can do this
new DialogPlusBuilder().blurBackground()
.buildCountriesListDialog(true,new DialogPlus.CountriesDialogListener() {
#Override
public void onItemClicked(CountryDataModel countryDataModel, DialogPlus dialogPlus) {
super.onItemClicked(countryDataModel, dialogPlus);
Toast.makeText(MainActivity.this,countryDataModel.getName()+ countryDataModel.getPhone_code(), Toast.LENGTH_SHORT).show();
}
})
.show(this.getSupportFragmentManager(), "Countries List Dialog");
I use volley library to get data from database i use this code
public class R_arabic extends AppCompatActivity {
RequestQueue requestQueue;
ListView listView;
ArrayList<listitem_gib> listitems = new ArrayList<listitem_gib>();
String name, img, url, num;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_r_arabic);
listView = (ListView) findViewById(R.id.listView);
TextView textView_Title = (TextView) findViewById(R.id.textView2);
Intent intent = getIntent();
String story_type = intent.getStringExtra("story_type");
switch (story_type) {
case "arabic":
textView_Title.setText("arabic");
break;
case "romance":
textView_Title.setText("romance");
break;
case "motrgm":
textView_Title.setText("motrgm");
break;
case "ro3b":
textView_Title.setText("ro3b");
break;
case "siasa":
textView_Title.setText("siasa");
break;
}
String url = "http://grassyhat.com/android/" + story_type + ".php";
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("all");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject respons = jsonArray.getJSONObject(i);
String id = respons.getString("id");
String name = respons.getString("name");
String img = respons.getString("img");
String url = respons.getString("url");
String num = respons.getString("num");
listitems.add(new listitem_gib(id, name, img, url, num));
}
} catch (JSONException e) {
e.printStackTrace();
}
listAllItme();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
}
public void listAllItme() {
ListAdapter lA = new listAdapter(listitems);
listView.setAdapter(lA);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckInternetConnection cic = new CheckInternetConnection(getApplicationContext());
Boolean Ch = cic.isConnectingToInternet();
if (!Ch) {
Toast.makeText(R_arabic.this, "no connection", Toast.LENGTH_LONG).show();
} else {
Intent open = new Intent(R_arabic.this, rewaya_show.class);
open.putExtra("name", listitems.get(position).name);
open.putExtra("url", listitems.get(position).url);
open.putExtra("img", listitems.get(position).img);
open.putExtra("num", listitems.get(position).num);
startActivity(open);
showad++;
if (showad >= 5) {
showad = 0;
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
}
}
});
}
class listAdapter extends BaseAdapter {
ArrayList<listitem_gib> lista = new ArrayList<listitem_gib>();
public listAdapter(ArrayList<listitem_gib> lista) {
this.lista = lista;
}
#Override
public int getCount() {
return lista.size();
}
#Override
public Object getItem(int position) {
return lista.get(position).name;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
View view = layoutInflater.inflate(R.layout.row_item_gib, null);
TextView name = (TextView) view.findViewById(R.id.textView_gib);
ImageView img = (ImageView) view.findViewById(R.id.imageView_gib);
TextView num = (TextView) view.findViewById(R.id.textView_gib2);
name.setText(lista.get(position).name);
num.setText(lista.get(position).num);
Picasso.with(R_arabic.this).load("http://grassyhat.com/android/image/" + lista.get(position).img).into(img);
return view;
}
}
i want to add progress bar while data loading to avoid blank page
sorry i'm new in android and i google for that and don't get useful answer
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.kamal.ahmed.rewaya.R_arabic"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:background="#drawable/bg"
tools:showIn="#layout/app_bar_r_arabic">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/adView">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="40sp"
android:textStyle="bold"
android:textColor="#e873400c"
android:layout_gravity="center"
android:id="#+id/textView2" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:paddingRight="#dimen/activity_horizontal_margin"
android:divider="#drawable/div1"
android:dividerHeight="35dp" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/progress_layout"
android:visibility="gone">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="100dp"
android:layout_marginBottom="60dp"
android:layout_weight="1"/>
<TextView
android:text="Download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progress_txt"
android:textSize="30sp"
android:textStyle="bold"
android:textColor="#e873400c"
android:layout_gravity="center"
android:layout_marginRight="90dp"
android:layout_marginBottom="60dp"
android:layout_weight="1" />
</LinearLayout>
Add progressBar in your activity_r_arabic
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
add ProgessBar progressBar; as global variable in your activity
and initialise it as
progressBar = (ProgessBar) findViewById(R.id.progress_bar);
and then In onResponse(JSONObject response) method add following line
progressBar.setVisibility(View.GONE)
EDIT
Make your linearLayout visible in xml
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/progress_layout"
android:visibility="visible">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="100dp"
android:layout_marginBottom="60dp"
android:layout_weight="1"/>
<TextView
android:text="Download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progress_txt"
android:textSize="30sp"
android:textStyle="bold"
android:textColor="#e873400c"
android:layout_gravity="center"
android:layout_marginRight="90dp"
android:layout_marginBottom="60dp"
android:layout_weight="1" />
</LinearLayout>
and inside onResponse(JSONObject response) method add following line
progress_layout.setVisibility(View.GONE)
I have the following problem.
A date picker where i select a date, this gets put into an array with the username.The array used to get the users start times by using the GetMemberPatrolStartTimes in Parser.This returns the JSON object that is then sent to the patrol history which populates a spinner.
I can see that the spinner gets populated but as soon as i click to drop the spinner down i get the error that is attached in the file.
Now i can read the error, but using it to solve the problem i can not get right.
Appreciate all help, guidance and any constructive criticism
Error: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
This is being caught in a UncaughtException method
eyeWatchApi.java
public JSONObject GetMemberPatrolStartTimes(ArrayList<String> details)throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","eyeWatchApi");
o.put("method", "GetMemberPatrolStartTimes");
p.put("details",mapObject(details));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
Parser.java
public Object GetPatrolHistoryStartTimes(JSONObject object){
String[] id_Array;
String[] time_Array;
try{
JSONArray a = object.getJSONArray("Value");
id_Array = new String[a.length()];
time_Array = new String[a.length()];
for (int i = 0; i < a.length(); i++) {
JSONObject b = a.getJSONObject(i);
id_Array[i]=b.getString("startID");
time_Array[i]=b.getString("startTime");
return new Object[]{id_Array,time_Array};
}
}catch (JSONException e){
return e;
}catch (Exception e){
return e;
}
return null;
}
Patrol_History.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.patrol_history,container,false);
timeSpinner = (Spinner) view.findViewById(R.id.TimeSpinner);
timeSpinner.setOnItemSelectedListener(this);
}
#Override
public void onClick(View view)
{
switch(view.getId())
{
case R.id.load_polly_btn :
{
drawpoliline();
break;
}
case R.id.select_date_txt :
{
Date_Pick_Dialog picker = new Date_Pick_Dialog();
picker.setDatePickerDialogFragmentEvents(this);
picker.show(getFragmentManager(), "datePicker");
break;
}
default:
{
break;
}
}
}
#Override
public void onDateSelected(String _date) {
patrolHistoryManager = new PatrolHistoryManager(getActivity());
patrolHistoryManager.setDate(_date);
selectDate_tv.setText(_date);
date = _date;
new AsyncSendDetails().execute(date);
//new AsyncGetAvailibleSlots().execute(_date);
}
public class AsyncSendDetails extends AsyncTask<String, Void, Object[]> {
#Override
protected Object[] doInBackground(String... params) {
eyeWatchApi api = new eyeWatchApi();
Parser parser = new Parser();
detailsList = new ArrayList<String>();
detailsList.add(userName);
detailsList.add(params[0]);
Object[] ob = new Object[0];
try {
ob = (Object[]) parser.GetPatrolHistoryStartTimes(api.GetMemberPatrolStartTimes(detailsList));
} catch (Exception e) {
e.printStackTrace();
}
return ob;
}
#Override
protected void onPostExecute(Object[] ob) {
if(ob != null)
{
timeID = (String[]) ob[0];
times = (String[]) ob[1];
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), R.layout.countries_spinner_item, times);
dataAdapter.setDropDownViewResource(R.layout.countries_spinner_item_droplist);
timeSpinner.setAdapter(dataAdapter);
}
else
{
Toast.makeText(getActivity(),"No Slots Available",Toast.LENGTH_LONG).show();
}
}
}
Layout File
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/black">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Select Date"
android:textAlignment="center"
android:textColor="#d32f2f"
android:cursorVisible="false"
android:shadowColor="#color/black"
android:id="#+id/select_date_txt"
android:layout_gravity="top|right"
android:text="02/05/2016"
android:paddingRight="15dp"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/white"
android:layout_below="#+id/select_date_txt"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/relativeLayout2" />
<Spinner
android:id="#+id/TimeSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#d32f2f"
android:layout_below="#+id/select_date_txt"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</Spinner>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="2dp"
android:paddingBottom="2dp"
android:background="#color/primary"
android:id="#+id/relativeLayout"
android:layout_below="#+id/TimeSpinner"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/relativeLayout">
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_weight="0.73"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</fragment>
<android.support.v7.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load Lines"
android:id="#+id/load_polly_btn"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</LinearLayout>
After almost a week of struggling i have just found the answer so i will be keeping it on here for all to see if there is a need for it
**Parser.java**
public Object GetPatrolHistoryStartTimes(JSONObject object){
String[] id_Array;
String[] time_Array;
try{
JSONArray a = object.getJSONArray("Value");
id_Array = new String[a.length()];
time_Array = new String[a.length()];
for (int i = 0; i < a.length(); i++) {
JSONObject b = a.getJSONObject(i);
id_Array[i]=b.getString("startID");
time_Array[i]=b.getString("startTime");
}
return new Object[]{id_Array,time_Array};
}catch (JSONException e){
return e;
}catch (Exception e){
return e;
}
return null;
}
The problem was that my return of the object should not have been inside the for statement but rather after it, after the loop has been completed