JSON Object to Spinner crash app - java

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

Related

RecyclerView doesn't Update and shows on screen until Soft Keyboard is Open/Close

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.

Add Progress bar while data loading from database

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)

populating alert dialog with list view,JSON

I am trying to fill an alert dialog with a JSON response how ever i am getting the following error :
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
i have inflated the list view in the onCreate as other posts suggest
i have included all relevant xml and java code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<CheckedTextView
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="?listPreferredItemHeightSmall"
android:checkMark="?android:attr/listChoiceIndicatorSingle"
android:gravity="center_vertical"
android:paddingLeft="?listPreferredItemPaddingLeft"
android:paddingRight="?listPreferredItemPaddingRight"
android:textAppearance="?textAppearanceListItemSmall" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/colorPrimary"
tools:context=".Queue.QueueStatusFragment">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listviewResp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingTop="15dp"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
public class QueueStatusFragment extends Fragment{
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
private TextView txtQueue;
private TextView txtCust;
private TextView txtTime;
private TextView txtBranch;
private String urlString;
private Button btnLeave;
private int reasonId;
ListView list;
public QueueStatusFragment()
{}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_queuestatus, container, false);
txtQueue = (TextView) v.findViewById(R.id.txtQueue);
txtTime = (TextView) v.findViewById(R.id.txtTime);
txtCust = (TextView) v.findViewById(R.id.txtCust);
txtBranch = (TextView) v.findViewById(R.id.txtBranch);
list=(ListView)v.findViewById(R.id.listviewResp);
btnLeave = (Button) v.findViewById(R.id.btnLeave);
SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
urlString = "http://172.20.10.5:1012/easyQ.svc/rest/queueDetails/" + globalVariable.getCustId();
new ProcessJson().execute(urlString);
System.out.println("works");
btnLeave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(
getActivity()).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("You are about to leave the queue, are you sure?");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
urlString = "http://172.20.10.5:1012/easyQ.svc/rest/reasons";
new getReasons().execute(urlString);
for(int i = 0; i < oslist.size();i++)
{
String id = oslist.get(i).get("id");
System.out.println(id);
}
}
});
alertDialog.show();
// SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
//String urlString1 = "http://172.20.10.5:1012/easyQ.svc/rest/leaveQueue";
// new JsonHandler().execute(urlString1);
//System.out.println("works");
}
});
// Inflate the layout for this fragment
return v;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
private class ProcessJson extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strings) {
String stream;
String urlString = strings[0];
HTTPDataHandler hh = new HTTPDataHandler();
stream = hh.GetHTTPData(urlString);
// Return the data from specified url
System.out.println(stream);
return stream;
}
protected void onPostExecute(String stream) {
if (stream != null) {
String[] array = stream.split(",");
String part1 = array[1];
String part2 = array[2];
String part3 = array[3];
String part4 = array[4];
String queueId = array[5];
SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
globalVariable.setQueueId(queueId);
if (part1 != null && part2 != null && part3 != null) {
int minutes = (int) Integer.parseInt(part1) / 60;
txtBranch.append("Branch Name: " + part4);
txtQueue.append("Service Name: " + part3);
txtCust.append("Queue Position: " + part2);
txtTime.append("Waiting Time: " + minutes + " minutes");
}
}
}
}
private class getReasons extends AsyncTask<String, Void, String>{
protected String doInBackground(String... strings) {
String stream;
String urlString = strings[0];
HTTPDataHandler hh = new HTTPDataHandler();
stream = hh.GetHTTPData(urlString);
// Return the data from specified url
System.out.println(stream);
return stream;
}
protected void onPostExecute(String stream) {
if (stream != null)
{
try
{
JSONObject object = new JSONObject(stream);
JSONArray array = object.getJSONArray("reasonsResult");
for(int i = 0 ; i < array.length(); i++) {
JSONObject reasonObj = array.getJSONObject(i);
String ID = reasonObj.getString("reason_leaving_id");
String reason = reasonObj.getString("description");
HashMap<String, String> map = new HashMap<String, String>();
map.put("description", reason);
map.put("id", ID);
oslist.add(map);
}
AlertDialog alertDialog = new AlertDialog.Builder(
getActivity()).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("You are about to leave the queue, are you sure?");
for(int i = 0; i < oslist.size(); i++)
{
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.dialog_list,
new String[] { "description"}, new int[] {
R.id.text1});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String branchId = oslist.get(+position).get("id");
final SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
globalVariable.setBranchId(branchId);
Fragment fragment = null;
fragment = new JoinFragment();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container_body, fragment).commit();
}
});
}
alertDialog.show();
}
catch(JSONException e)
{
e.printStackTrace();
}
}
}
}
private class JsonHandler extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strings) {
String stream;
String urlString = strings[0];
HTTPDataHandler hh = new HTTPDataHandler();
final SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
System.out.println("sssss" + globalVariable.getQueueId() + globalVariable.getCustId());
JSONObject sender = new JSONObject();
try {
sender.put("queueid", globalVariable.getQueueId());
sender.put("customerid", globalVariable.getCustId());
//sender.put("reasonid",);
} catch (JSONException e) {
e.printStackTrace();
}
stream = hh.POST(urlString, sender);
// Return the data from specified url
System.out.println(stream);
return stream;
}
protected void onPostExecute(String stream) {
if (stream != null) {
if (stream.equals("\"Successful\"")) {
Toast.makeText(getActivity().getApplicationContext(),
"Successfully left Queue", Toast.LENGTH_LONG).show();
Fragment fragment=null;
fragment=new HomeFragment();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container_body, fragment).commit();
} else if (stream.equals("\"Not Exist\"")) {
Toast.makeText(getActivity().getApplicationContext(),
"Unable to leave Queue", Toast.LENGTH_LONG).show();
} else if (stream.equals("\"Not exist\"")) {
Toast.makeText(getActivity().getApplicationContext(),
"Not in queue", Toast.LENGTH_LONG).show();
}
}
}
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/colorPrimary"
tools:context=".Queue.QueueStatusFragment" >
<TextView
android:id="#+id/txtBranch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8"
android:layout_centerHorizontal="true"
android:layout_centerInParent="false"
android:text="hello"
android:layout_marginTop="100dp"
android:gravity="center|left"
android:textColor="#ffffff"
android:textColorHint="#ffffff" />
<TextView
android:id="#+id/txtQueue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8"
android:text="hello1"
android:layout_marginTop="160dp"
android:gravity="center|left"
android:textColor="#ffffff"
android:layout_centerHorizontal="true"
android:layout_centerInParent="false"
android:textColorHint="#ffffff" />
<TextView
android:id="#+id/txtTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8"
android:text="hello2"
android:gravity="center|left"
android:layout_marginTop="44dp"
android:layout_centerInParent="false"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:layout_below="#+id/txtQueue"
android:layout_alignStart="#+id/txtQueue" />
<TextView
android:id="#+id/txtCust"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="8"
android:text="hello3"
android:gravity="center|left"
android:textColor="#ffffff"
android:layout_marginTop="47dp"
android:layout_centerInParent="false"
android:textColorHint="#ffffff"
android:layout_below="#+id/txtTime"
android:layout_alignStart="#+id/txtTime" />
<Button
android:id="#+id/btnLeave"
android:layout_width="312dp"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:gravity="center"
android:text="Leave Queue"
android:textColor="#ffffff"
android:textStyle="bold"
android:layout_marginBottom="65dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
I think your problem is in your fragment_queuestatus there is no Listview. Which you add the previous layout. That why it's not get the listview and when you try to set the adapter it's thing you set something in a NULL object. So, Add the ListView in the fragment_queuestatus layout. That will solve the problem.

how to show default list in spinner in android

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

Drawable not displaying in ImageView

Hello I am running into a silly error and I think I might be missing something. I currently have a list of objects. The objects have a title, description and an image. The title and description display properly, but for some reason the Image won't. I added the objects on another activity and made a list, when the user selects the item they wanted to see it send the id to this new page where it pulls the object. I added a random image as jpg to the application to see if it pulse and it does, but it looks a little weird. Any ideas why the images won't be pulling from the list? Thank you in advance.
XML:
<?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">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/img"
android:src="#drawable/img"
android:layout_alignParentTop="true"
android:layout_alignParentStart="false"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="News Title"
android:id="#+id/title"
android:layout_below="#+id/img"
android:layout_alignParentLeft="false"
android:layout_alignParentRight="false"
android:layout_centerInParent="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/desc"
android:layout_below="#+id/title"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
JAVA:
CustomOBJ selOBJ = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.det);
Bundle objID = getIntent().getExtras();
for(int x = 0; x < MainActivity.listobjs.size(); x++){
if (MainActivity.listobjs.get(x).getID().equals(objID.getString("object") )){
selOBJ = MainActivity.listobjs.get(x);
break;
}
}
TextView Title =(TextView)findViewById(R.id.title);
TextView description = (TextView)findViewById(R.id.desc);
ImageView objPic=(ImageView)findViewById(R.id.img);
Title.setText(selOBJ.getName());
description.setText(selOBJ.getDescription());
objPic.setImageDrawable(selOBJ.getObjPic());
}
CustomOBJ Class:
public class CustomOBJ {
private String objID;
private String name;
private String Description;
private Drawable objPic;
public CustomOBJ(String i, String n, String d, Drawable pic) {
objID = i;
name = n;
Description = d;
objPic = pic;
}
public String getID() { return objID; }
public String getName() {return name;}
public String getDescription() {return description;}
public Drawable getObjPic() {return objPic; }
}
MainActivity:
public void jsonTolist(){
//parse json data
try{
jArray = new JSONArray(welcome.result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag", "title:" + json_data.getString("title")
);
if(listobjs.isEmpty() || isNewsName(listobjs,json_data) == false){
Drawable drawable = LoadImageFromWebOperations(json_data.getString("img"));
selOBJ = new CustomOBJ(json_data.getString("id"), json_data.getString("title"), json_data.getString("desc"), drawable);
listobjs.add(selOBJ);
}
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
Load Images:
private Drawable LoadImageFromWebOperations(String url){
try{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e) {
System.out.println("Exc="+e);
return null;
}
}
Sender Side:
Bundle d1 = new Bundle();
d1.putInt("d",0);
Receiver Side:
Bundle objID = getIntent().getExtras();
int x = objID .getInt("d");
if (MainActivity.listobjs.get(x).getID()
.equals(objID.getString("object") ))
{
selOBJ = MainActivity.listobjs.get(x);
}
Before doing this kindly check CustomOBJ class have a valid constructor or not.
ref this link also
How to get image from url website in imageview in android

Categories