Sorry if the heading is misleading, i couldn't quite put it in words.
Rotten Tomatoes
The list runs fine and looks fine for what i am doing. What i am planning on doing is have a details page now with the synopsis etc. I thought about passing the ID of the movie that is passed on.
If i click on a movie, how can i, in the next page set the image of that movie, the text etc. Basically get all the data i need from the selected movie?
The source code can be found here - Github
Screenshot (Terrible looking but its just messing around):
Thanks
I was having the same problemm in my project but your seems similar so i will give you my solution in order to help.
In my case i was retrieving stocks from a database and each stock had extra 15 prices which i wanted to show everytime i tapped on a stock so check the below answer.
Code:
I created an OBject with String[] to help me retrieve all those 15 prices for each stock and then pass it through Intent.
public class StockList {
private String stockCurrentName;
private String stockCurrentPrice;
private String stockImage;
private String[] restPrices;
public StockList(String stockCurrentName, String stockCurrentPrice, String stockImage, String[] restPrices) {
this.stockCurrentName = stockCurrentName;
this.stockCurrentPrice = stockCurrentPrice;
this.stockImage = stockImage;
this.restPrices = restPrices;
}
public String getStockCurrentName() {
return stockCurrentName;
}
public void setStockCurrentName(String stockCurrentName) {
this.stockCurrentName = stockCurrentName;
}
public String getStockCurrentPrice() {
return stockCurrentPrice;
}
public void setStockCurrentPrice(String stockCurrentPrice) {
this.stockCurrentPrice = stockCurrentPrice;
}
public String getStockImage() {
return stockImage;
}
public void setStockImage(String stockImage) {
this.stockImage = stockImage;
}
public String[] getRestPrices() {
return restPrices;
}
public void setRestPrices(String[] restPrices) {
this.restPrices = restPrices;
}
}
Then is how i retrieved the data:
public class JsonReadTask extends AsyncTask<String, Void, String> {
public JsonReadTask() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListLoaderActivity.this);
pDialog.setTitle(R.string.waiting);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage(getString(R.string.get_stocks));
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.setInverseBackgroundForced(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
} catch (Exception e) {
Intent intent1 = new Intent(ListLoaderActivity.this,
RefreshActivity.class);
startActivity(intent1);
ListLoaderActivity.this.finish();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (Exception e) {
Intent intent1 = new Intent(ListLoaderActivity.this,
RefreshActivity.class);
startActivity(intent1);
ListLoaderActivity.this.finish();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrawer();
pDialog.dismiss();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
task.execute(new String[]{url});
}
public void ListDrawer() {
customList = new ArrayList<StockList>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("metoxes");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
//for each stock i get its prices.
//In your List for each movie you can get its synopsis and anything else you need.
name = jsonChildNode.optString("name");
price = jsonChildNode.optString("price");
price1 = jsonChildNode.optString("price1");
price2 = jsonChildNode.optString("price2");
price3 = jsonChildNode.optString("price3");
price4 = jsonChildNode.optString("price4");
price5 = jsonChildNode.optString("price5");
price6 = jsonChildNode.optString("price6");
price7 = jsonChildNode.optString("price7");
price8 = jsonChildNode.optString("price8");
price9 = jsonChildNode.optString("price9");
price10 = jsonChildNode.optString("price10");
price11 = jsonChildNode.optString("price11");
price12 = jsonChildNode.optString("price12");
price13 = jsonChildNode.optString("price13");
price14 = jsonChildNode.optString("price14");
price15 = jsonChildNode.optString("price15");
image = jsonChildNode.optString("image");
justPrices = new String[]{price1, price2,
price3, price4, price5, price6, price7, price8, price9,
price10, price11, price12, price13, price14, price15};
loipesTimes = new String[]{"1st Day Value " + price1, "2nd Day Value " + price2, "3rd Day Value " + price3, "4th Day Value " + price4, "5th Day Value " + price5,
"6th Day Value " + price6, "7th Day Value " + price7, "8th Day Value " + price8, "9th Day Value " + price9,
"10th Day Value " + price10, "11th Day Value " + price11, "12th Day Value " + price12, "13th Day Value " + price13, "14th Day Value " + price14, "15th Day Value " + price15};
customList.add(new StockList(name, price, image, justPrices));
}
} catch (Exception e) {
Intent intent1 = new Intent(ListLoaderActivity.this,
RefreshActivity.class);
startActivity(intent1);
ListLoaderActivity.this.finish();
}
ArrayAdapter adapter = new MyStocksAdapter(ListLoaderActivity.this, R.layout.list_item, customList);
adapter.notifyDataSetChanged();
startList.setAdapter(adapter);
}
And then pass the through Intent
private void registerCallClickBack() {
startList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
tv1 = (TextView) viewClicked.findViewById(R.id.stock_name);
tv2 = (TextView) viewClicked.findViewById(R.id.stock_price);
Intent intent = new Intent(ListLoaderActivity.this, StockItem.class);
intent.putExtra("name", tv1.getText().toString());
intent.putExtra("price", tv2.getText().toString());
intent.putExtra("stockInfo", customList.get(position).getRestPrices());
intent.putExtra("stockImage", customList.get(position).getStockImage());
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
}
}
}
I guess you can use it like this and this will help you get it done!!!
Hope i helped you!!!
if you show us what are you doing in your code we could help you more but to pass data from one activity to another you can use intent example :
String value= getIntent().getStringExtra("keyName");
Intent intent = new Intent(this, RatingDescriptionSearchActivity.class);
intent.putExtra("keyName", value);
startActivity(intent);
You should do something like this:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
YourObject item = arraylist.get(arg2);
TextView textView = (TextView) arg1.findViewById(R.id.textView);
Intent intent = new Intent(ThisActivity.this, SecondActivity.class);
intent.putExtra("textview_value", textView.getText().toString());
startActivity(intent);
}
}
});
you can use intent for pass data from one activity to another exactly how Moudiz say and then retrieve received data like this
String value;
Intent intent = getIntent();
value = intent.getStringExtra("keyName");
If you would have pasted your code then it would be easier to understand your actual problem . But with the data and json given :
1.if you having problem in retrieving data from Json then please follow below link :
http://www.androidhive.info/2012/01/android-json-parsing-tutorial
If passing to next Activity then it would be done using Intent:
String value= getIntent().getStringExtra("Key");
Intent intent = new Intent(this, DataClassNameHere.class);
intent.putExtra("key", value);
startActivity(intent);
Related
I am developing an app, wherein I get JSON data and I am displaying it in the recylcer view. Now on click to the recycler view, on the basis of the item clicked I need to fetch the JSON data from the server and display it in the same recycler view. Its kind of recursive function. I am unable to find anything.
In the MainActivity, I have created an inner class for doing network task
new LauncherLoadThread(rootView).execute(appUsername, appPassword, loadURL, path);
class LauncherLoadThread extends AsyncTask<String, Integer, String[]> {
private View rootView;
public LauncherLoadThread(View rootView) {
this.rootView = rootView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String[] strings) {
super.onPostExecute(strings);
progressBar.setVisibility(View.GONE);
if (strings != null) {
if (strings[0].contentEquals("200")) {
try {
String data = strings[1];
Log.d("Data", data);
JSONArray allData = new JSONArray(data);
for (int i = 0; i < allData.length(); i++) {
JSONObject jsonObject = allData.getJSONObject(i);
String id = jsonObject.getString("id");
String name = jsonObject.getString("name");
String path = jsonObject.getString("path");
String leaf = jsonObject.getString("leaf");
Log.d("Loaded Data: ", "Id: " + id + ". name: " + name + ". Path: " + path);
LauncherModel launcherModel=new LauncherModel(id,name,leaf,path);
launcherModelList.add(launcherModel);
}
adapter=new LauncherAdapter(launcherModelList,getContext());
launcherRecyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Snackbar snackbar = Snackbar.make(rootView, strings[0] + " Something broke down.", Snackbar.LENGTH_LONG);
View snackBarView = snackbar.getView();
TextView tv = (TextView) snackBarView.findViewById(android.support.design.R.id.snackbar_text);
snackbar.show();
}
} else {
Snackbar snackbar = Snackbar.make(rootView, "Oops something went wrong.", Snackbar.LENGTH_LONG);
View snackBarView = snackbar.getView();
TextView tv = (TextView) snackBarView.findViewById(android.support.design.R.id.snackbar_text);
snackbar.show();
}
}
#Override
protected String[] doInBackground(String... strings) {
String username = strings[0];
String password = strings[1];
String url = strings[2];
String path=strings[3];
String processURL="";
if(path.equals("")) {
processURL=url+"?path=Library";
}else {
processURL=url+"?path=" + path;
}
Log.d("doInBackURL", url);
String credential = Credentials.basic(username, password);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.get()
.addHeader("authorization", credential)
.addHeader("content-type", "application/json")
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
String body = response.body().string();
Log.d("Body--->",body);
String code = response.code() + "";
Log.d("Code--->",code);
String[] output = {code, body};
return output;
} else {
String body = "Error: 404";
String code = response.code() + "";
String[] output = {code, body};
return output;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Here is my adapter onClickMethod:
public void onBindViewHolder(LauncherViewHolder holder, int position) {
LauncherModel launcherModel = listItem.get(position);
.......
.......
.......
.......
.......
.......
holder.launcherItemRelativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
Here you have many options depending on architecture you using. Basically, you can create interface like MyCustomItemClickListener:
interface MyCustomItemClickListener {
void onClick();
}
Than you extend MyCustomItemClickListener by Activity related to RecyclerView and override its method:
#Override
public void onClick(){
// basically, here goes the logic you want on click
}
As I assume you already have ViewHolder in Adapter, the simple option would be to pass Activity as custom Listener in your `Adapter. Than, if we choose this option, it should work like this:
//adapter's inner
class SomeClassViewHolder(val view: View) extends RecyclerView.ViewHolder(view) {
//here can be view initializing, like
txtHeader = (TextView) view.findViewById(R.id.audio_subtitle);
void bind(int position){
// all view binding logic goes here, for example:
txtHeader.setText("someText");
// AND here is also your listener working:
view.setOnClickListener{
listener.onItemClick(item)
}
}
}
//and then in adapter
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
holder.bind(values.get(position));
}
The only trick here is to pass the view(Activity or Fragment) as listener to custom Adapter and it should work.
Edit: For sure, with this approach you can simply reload data from activity with your own logic, like make another async request.
You can simply call notifyDataSetChanged() function of Adapter class.
I'm creating an android application which allow the user to put his tab and its exercises, set and reps.
I'm retrieving the days of the week that the user checked, so I'd like to take the days to another activity. These are the step:
USER CHECK DAYS OF THE WEEK -> NEW ACTIVITY WELL BE OPEN, IT WILL ASK YOU TO PUT TWO MUSCOLAR GROUPS FOR EVERY DAY YOU CHOOSE.
Example:
User choose: Monday, tuesday and saturday, next step, MONDAY: lat and shoulder ; TUESDAY: triceps and biceps; The problem is that I'm not able to understand how can I remember the days that the user choose. I tried to get some algorithms but I'm stack to the first day he choose and I don't know how to increase it.
Xml image:
First step
Second step
Instead of &day1, there should be the days he checked one by one.
Java source:
static Global g = new Global();
private Button nextconfig;
private Spinner gruppo1,gruppo2;
private TextView giorno;
String[] array ;
String [] arrayTwo;
String idSelectedSpinner1, idSelectedSpinner2;
String id;
String name;
String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
int[] daysBool;
int countClick=1;
int countButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_starting_2);
nextconfig = (Button) findViewById(R.id.nextconfig);
gruppo1=(Spinner) findViewById(R.id.gruppo1);
gruppo2=(Spinner) findViewById(R.id.gruppo2);
giorno=(TextView) findViewById(R.id.giorno1);
Intent intent = getIntent();
int conta=intent.getIntExtra("countButton",0);
countButton=conta;
final SharedPreferences mPrefs = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
gruppo1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
idSelectedSpinner1=arrayTwo[position];
Log.d("idSpinner:","" + arrayTwo[position]);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
gruppo2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
idSelectedSpinner2=arrayTwo[position];
Log.d("idSpinner:","" + arrayTwo[position]);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
final String url = g.getRootServer() + "/getMuscolarGroups.php";
final String urlDays = g.getRootServer() + "/getTab.php?token="+mPrefs.getString("token",null);
JsonObjectRequest myRequest = new JsonObjectRequest(Request.Method.GET, url, new JSONObject(), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("RESPONSE", response.toString());
if (response.has("errorCode")) {
try {
if (response.getInt("errorCode") == 0) {
JSONObject data = response.getJSONObject("data");
JSONArray muscolarGroups = data.getJSONArray("muscolarGroups");
array= new String [muscolarGroups.length()];
arrayTwo= new String [muscolarGroups.length()];
for (int i=0;i<muscolarGroups.length();i++){
JSONObject muscolarData = muscolarGroups.getJSONObject(i);
id = muscolarData.getString("id");
name = muscolarData.getString("name");
array[i]=name;
arrayTwo[i]=id;
}
addToSpinner(array);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
};
MySingleton.getInstance(getBaseContext()).addToRequestQueue(myRequest);
Log.d("REQUEST", myRequest.toString());
JsonObjectRequest myRequestDays = new JsonObjectRequest(Request.Method.GET, urlDays, new JSONObject(), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("RESPONSE", response.toString());
if (response.has("errorCode")) {
Log.d("response","" + response);
try {
if (response.getInt("errorCode") == 0) {
JSONObject data = response.getJSONObject("data");
JSONObject tab = data.getJSONObject("tab");
daysBool = new int[tab.length() -1];
int monday = tab.getInt("monday");
int tuesday = tab.getInt("tuesday");
int wednesday = tab.getInt("wednesday");
int thursday = tab.getInt("thursday");
int friday = tab.getInt("friday");
int saturday = tab.getInt("saturday");
Log.d("Saturday", " "+saturday);
daysBool[0] = monday;
daysBool[1] = tuesday;
daysBool[2] = wednesday;
daysBool[3] = thursday;
daysBool[4] = friday;
daysBool[5] = saturday;
if (monday == 1) {
giorno.setText(days[0]);
} else if (tuesday == 1) {
giorno.setText(days[1]);
} else if (wednesday == 1) {
giorno.setText(days[2]);
} else if (thursday == 1) {
giorno.setText(days[3]);
}else if (friday == 1) {
giorno.setText(days[4]);
}else if (saturday == 1) {
giorno.setText(days[5]);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
};
MySingleton.getInstance(getBaseContext()).addToRequestQueue(myRequestDays);
Log.d("REQUEST", myRequestDays.toString());
nextconfig.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String url = g.getRootServer() + "/setTabGroup.php?token=" + mPrefs.getString("token",null) + "&groupOneId=" + idSelectedSpinner1 + "&groupTwoId=" + idSelectedSpinner2 +"&dayNumber=3";
final Map<String, String> params = new HashMap<>();
//Parametri
params.put("token","token"+mPrefs.getString("token",null));
params.put("groupOneId","groupOneId"+idSelectedSpinner1);
params.put("groupTwoId","groupTwoId" +idSelectedSpinner2);
params.put("dayNumber","dayNumber" +idSelectedSpinner2);
JsonObjectRequest myRequest = new JsonObjectRequest(Request.Method.GET, url, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("RESPONSE", response.toString());
if (response.has("errorCode"))
{
try {
if (response.getInt("errorCode") == 0) {
if (countClick==countButton){
Intent intent = new Intent(getBaseContext(), Gruppo.class);
intent.putExtra("daysTab",days);
intent.putExtra("daysTabBool",daysBool);
startActivity(intent);
finish();
}
countClick++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
};
MySingleton.getInstance(getBaseContext()).addToRequestQueue(myRequest);
Log.d("REQUEST", myRequest.toString());
}
});
}
void getDays() {
}
void addToSpinner(String[] array) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.spinner_item, array);
gruppo1.setAdapter(adapter);
gruppo2.setAdapter(adapter);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(getBaseContext(), TabStarting.class);
startActivity(intent);
finish();
}
}
I will not look at your code snippet, because that's like asking me to do the work for you. Instead, I will answer you at a very high level, because this is really basic droid, and if you spend 5m on google, you'll find plenty of material on this topic.
The days of your first image are your 'state', each day can either be selected or not selected, and the views know that. Once you click the button, you start a new activity: at this point, pass the 'state' to the new activity with an intent. On the other side, on the created activity, you'll obtain the state, and by that info you'll populate your schedule with the selected days.
Hope it helps!
I am trying to create a shopping cart app and everything was going great but now i am stuck for last three day did search lot in stackoverflow but could not get a answer.I am populating listview from server and there is two buttons in each row plus(for adding quantity) and minus for (decrements it). This is the screen where i am adding quantity to cart.
I am trying to insert row to sqlite database upon clicking either of two buttons and i have achieved this and i am show these data in next activity inside a listview. Here my problem starts when i insert data it shows it properly but during updation it is showing strange behavior. If i click on first three rows the insertion and updation working fine but if i scroll down and click on any item then instead of updating each time its inserting.. I know this question is quite big and lengthy but i could not find a good way to summarize it sorry.. Please help me thanks ..
This is the screen which i am getting as output.
Here is my ListView class.
public class MyFragment extends Fragment implements View.OnClickListener{
int mCurrentPage;
private ListView listView;
RecyclerView recyclerView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private ProgressDialog pDialog;
private List<FeedItem> productsInCart = new ArrayList<FeedItem>();
private RelativeLayout content;
private SharedPreferences preference;
TextView badge,prices;
int totalCount=0,newCount = 0;
int lastCount;
int totalPrice;
SQLiteDatabase dataBase;
public static final String TOTAL_COUNT = "count";
DBHelper mHelper;
boolean isUpdate;
String userId,price,pname,position;
private Button checkOut;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Getting the arguments to the Bundle object */
Bundle data = getArguments();
/** Getting integer data of the key current_page from the bundle */
mCurrentPage = data.getInt("current_page", 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.myfragment_layout, container, false);
recyclerView= (RecyclerView) v.findViewById(R.id.my_recycler_view);
content = (RelativeLayout)v.findViewById(R.id.content);
badge = (TextView)v.findViewById(R.id.all_comments);
checkOut = (Button)v.findViewById(R.id.checkOut);
prices = (TextView)v.findViewById(R.id.price);
feedItems = new ArrayList<FeedItem>();
new JSONAsyncTask()
.execute("http://api.androidhive.info/feed/feed.json");
listAdapter = new FeedListAdapter(getActivity(), feedItems);
recyclerView.setAdapter(listAdapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
listAdapter.setOnAddNum(this);
listAdapter.setOnSubNum(this);
mHelper=new DBHelper(getActivity());
content.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent(getActivity(),CheckOutFooter.class);
startActivity(i);
getActivity().overridePendingTransition
(R.anim.slide_in_bottom, R.anim.slide_out_bottom);
}
});
checkOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (userId != null){
Intent i = new Intent(getActivity(),CheckOut.class);
startActivity(i);
}
else{
Toast.makeText(getActivity(), "Cart is empty! Please add few products to cart.",
Toast.LENGTH_SHORT).show();
}
}
});
return v;
}
// TODO Auto-generated method stub
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("feed");
for (int i = 0; i < jarray.length(); i++) {
JSONObject feedObj = jarray.getJSONObject(i);
// Actors actor = new Actors();
FeedItem item = new FeedItem();
item.setObservation(feedObj.optString("name"));
item.setSummary(feedObj.optString("timeStamp"));
item.setName(feedObj.optString("name"));
feedItems.add(item);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
if(result == false){
Toast.makeText(getActivity(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
else{
listAdapter.notifyDataSetChanged();
}
pDialog.dismiss();
}
}
#Override
public void onClick(View view) {
Object tag = (Integer) view.getTag();
switch (view.getId()){
case R.id.btnAddToCart1:
// FeedItem item = feedItems.get(tag);
if (tag != null && tag instanceof Integer) {
int position = (Integer) tag;
int num =feedItems.get(position).getNum();
int price =feedItems.get(position).getPrice();
String pName = feedItems.get(position).getName();
String product_name = feedItems.get(position).getName();
num++;
feedItems.get(position).setNum(num);
feedItems.get(position).setPrice(position);
Toast.makeText(getActivity(),
product_name+ " is added to cart!", Toast.LENGTH_SHORT).show();
preference = getActivity().getSharedPreferences("STATE", Context.MODE_PRIVATE);
preference.edit().putString("QUANTITY", String.valueOf(num)).apply();
preference.edit().putString("PRICE", String.valueOf(num*position)).apply();
preference.edit().putString("PNAME",product_name).apply();
preference.edit().putString("POSITION",String.valueOf(position)).apply();
updateData();
listAdapter.notifyDataSetChanged();
}
break;
case R.id.btnAddToCart5:
if (tag != null && tag instanceof Integer) {
int position = (Integer) tag;
int num =feedItems.get(position).getNum();
int price =feedItems.get(position).getPrice();
if (num>0) {
num--;
feedItems.get(position).setNum(num);
feedItems.get(position).setPrice(position);
preference = getActivity().getSharedPreferences("STATE", Context.MODE_PRIVATE);
preference.edit().putString("QUANTITY", String.valueOf(num)).apply();
preference.edit().putString("PRICE", String.valueOf(num*position)).apply();
preference.edit().putString("POSITION",String.valueOf(position)).apply();
updateData();
listAdapter.notifyDataSetChanged();
}
else{
num= 0;
dataBase.delete(
DBHelper.TABLE_NAME,
DBHelper.KEY_ID + "="
+ (position+1), null);
listAdapter.notifyDataSetChanged();
}
}
break;
}
}
public void onResume(){
super.onResume();
}
private void updateData() {
preference =
getActivity().getSharedPreferences("STATE", Context.MODE_PRIVATE);
userId = preference.getString("QUANTITY", null);
price = preference.getString("PRICE", null);
pname = preference.getString("PNAME", null);
position = preference.getString("POSITION", null);
int counts = Integer.parseInt(position);
if(userId == null){
badge.setText("0");
}
else{
checkOut.setEnabled(true);
badge.setText(String.valueOf(userId));
dataBase = mHelper.getReadableDatabase();
/*Cursor curs = dataBase.rawQuery("SELECT SUM(price) FROM cart", null);
if(curs.moveToFirst())
{
int total = curs.getInt(0);
System.out.println("Total Sum of Price : "+total);
prices.setText(String.valueOf(total)+" Rs/-");
}
*/
Cursor cur = null;
String query = "SELECT * FROM " + DBHelper.TABLE_NAME +
" WHERE " +DBHelper.KEY_ID+"=?;" ;
cur = dataBase.rawQuery(query,new String[] {String.valueOf(counts+1)});
if((cur != null) && (cur.getCount() > 0)){
dataBase = mHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(DBHelper.KEY_COUNT,userId);
cv.put(DBHelper.KEY_PRICE, price);
cv.put(DBHelper.KEY_PNAME, pname);
System.out.println("Database values : "+cv);
dataBase.update(DBHelper.TABLE_NAME, cv, DBHelper.KEY_ID+" = '" +
String.valueOf(counts+1) + "'", null);
cur.close();
}
else{
dataBase = mHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(DBHelper.KEY_COUNT,userId);
cv.put(DBHelper.KEY_PRICE, price);
cv.put(DBHelper.KEY_PNAME, pname);
System.out.println("Database values : "+cv);
dataBase.insert(DBHelper.TABLE_NAME, null, cv);
cur.close();
}
}
}
}
My checkout page where i am showing data from sqlite.
public class CheckOut extends AppCompatActivity{
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> product_Name = new ArrayList<String>();
private ArrayList<String> product_Quantity = new ArrayList<String>();
private ArrayList<String> product_Price = new ArrayList<String>();
private ArrayList<Integer> quantityList = new ArrayList<Integer>();
private ArrayList<Integer> amountList = new ArrayList<Integer>();
ListView recyclerView;
TextView quantity;
TextView amount;
Button pay;
DBHelper mHelper;
SQLiteDatabase dataBase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkout);
recyclerView= (ListView) findViewById(R.id.my_recycler_view);
amount = (TextView) findViewById(R.id.amount);
quantity = (TextView) findViewById(R.id.quantity);
pay = (Button) findViewById(R.id.pay);
mHelper = new DBHelper(this);
}
#Override
protected void onResume() {
displayData();
super.onResume();
}
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM " + DBHelper.TABLE_NAME, null);
int sum = 0;
int qty = 0;
userId.clear();
product_Name.clear();
product_Quantity.clear();
quantityList.clear();
amountList.clear();
product_Price.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DBHelper.KEY_ID)));
product_Name.add(mCursor.getString(mCursor.getColumnIndex(DBHelper.KEY_PNAME)));
product_Quantity.add(mCursor.getString(mCursor.getColumnIndex(DBHelper.KEY_COUNT)));
product_Price.add(mCursor.getString(mCursor.getColumnIndex(DBHelper.KEY_PRICE)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(CheckOut.this,userId, product_Name, product_Price,product_Quantity);
recyclerView.setAdapter(disadpt);
mCursor.close();
quantityList = convertInteger(product_Quantity);
amountList = converAmountInteger(product_Price);
for (int i : quantityList){
qty = qty+i;
}
for (int s : amountList){
sum = sum +s;
}
amount.setText(String.valueOf(sum));
quantity.setText(String.valueOf(qty));
disadpt.notifyDataSetChanged();
}
private ArrayList<Integer> converAmountInteger(
ArrayList<String> product_Price2) {
// TODO Auto-generated method stub
ArrayList<Integer> result = new ArrayList<Integer>();
for(String amount : product_Price2) {
try {
//Convert String to Integer, and store it into integer array list.
result.add(Integer.parseInt(amount));
} catch(NumberFormatException nfe) {
//System.out.println("Could not parse " + nfe);
Log.w("NumberFormat", "Parsing failed! " + amount + " can not be an integer");
}
}
return result;
}
private ArrayList<Integer> convertInteger(
ArrayList<String> product_Quantity2) {
// TODO Auto-generated method stub
ArrayList<Integer> result = new ArrayList<Integer>();
for(String quantity : product_Quantity2) {
try {
//Convert String to Integer, and store it into integer array list.
result.add(Integer.parseInt(quantity));
} catch(NumberFormatException nfe) {
//System.out.println("Could not parse " + nfe);
Log.w("NumberFormat", "Parsing failed! " + quantity + " can not be an integer");
}
}
return result;
}
Database class:
public class DBHelper extends SQLiteOpenHelper {
public static String DATABASE_NAME="user.db";
public static final String TABLE_NAME="cart";
public static final String KEY_COUNT="cartItem";
public static final String KEY_PNAME="product_name";
public static final String KEY_ID="id";
public static final String KEY_PRICE="price";
public static final String KEY_CREATED_AT="created_at";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_COUNT+" INTEGER,"
+KEY_PNAME+" TEXT,"+KEY_PRICE+" INTEGER,"+ KEY_CREATED_AT
+ " DATETIME" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
UPDATE :
There was a little mistake i changed the column name instead of i created a unique key and its working fine..
I'm working on a school assignment which is to create a Bookmarking app with 2 activites, a ListActivity called BookNote and an activity called ManageActivity.
All typing must be done in ManageActivity and passed back to BookNote for list changes, reading, and writing data.
My problem is when I call the function "addBookmark" in BookNote activity. What I want to happen is for a new list item to be added at the end of the list with the bookmark objects info in it.
What is happening is that whatever item is at the end of the list is simply overwritten instead of a new item being created.
My code is below with comments stating my intentions of each function.
BookNote activity
public class BookNote extends ListActivity{
private ArrayAdapter<Bookmark> adapter;
private final String FILENAME = "bookmarks.txt";
public String title = "EMPTY", url = "EMPTY", note = "EMPTY";
public String bookmarkClicked ="";
public int listViewID = 0;
public boolean intentListener = false;
public int intentReturnCounter = 0;
public boolean addBookmarkClicked = false;
public ArrayList<Bookmark> bookmarkList;
/*When activity is called, list is populated by readData(), addBookmarkClicked is reset to false, intentLister is changed to true if returning from ManageActivity,
if intentListener is true, addBookmarkClicked will be changed to true if AddBookmark is clicked from the BookNote menubar, a bookmark object will be created with information
passed back from ManageActivity, and if addBookmarkClicked is true, the bookmark object will be added to the end of the list, otherwise it will be inserted in the same
list element from which was chosen to edit.*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bookmarkList = readData();
adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);
setListAdapter(adapter);
addBookmarkClicked = false;
intentListener = false;
intentListener = getIntent().getBooleanExtra("listen", false);
if (intentListener == true) {
addBookmarkClicked = getIntent().getExtras().getBoolean("addBookmarkClicked", false);
title = getIntent().getExtras().getString("title");
url = getIntent().getExtras().getString("url");
note = getIntent().getExtras().getString("note");
listViewID = getIntent().getExtras().getInt("listViewID");
Bookmark bookmark = new Bookmark(title, url, note);
Toast.makeText(getApplicationContext(), "Intent return: True", Toast.LENGTH_SHORT).show();
intentListener = false;
if (addBookmarkClicked == true) {
addBookmark(bookmark);
Toast.makeText(getApplicationContext(), "Bookmark Added", Toast.LENGTH_SHORT).show();
addBookmarkClicked = false;
} else {
insertBookmark(bookmark, listViewID);
Toast.makeText(getApplicationContext(), "Bookmark Edited", Toast.LENGTH_SHORT).show();
}
//writeData();
}
}
//reads data when app runs and fills arrayadapter and list with items saved to bookmarks.txt
private ArrayList<Bookmark> readData(){
ArrayList<Bookmark> bookmarks = new ArrayList<>();
try {
FileInputStream fis = openFileInput(FILENAME);
Scanner scanner = new Scanner(fis);
if (scanner.hasNext()){
String titleScan = scanner.nextLine();
String urlScan = scanner.nextLine();
String noteScan = scanner.nextLine();
Bookmark bookmark = new Bookmark(titleScan, urlScan, noteScan);
bookmarks.add(bookmark);
}else{
Bookmark bookmark = new Bookmark("Example Title", "Example URL", "Example Note");
bookmarks.add(bookmark);
}
scanner.close();
} catch (FileNotFoundException e) {
}
return bookmarks;
}
private void writeData(){
try {
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osw);
PrintWriter pw = new PrintWriter(bw);
for(int i = 0; i < adapter.getCount(); i++){
Bookmark bookmark = adapter.getItem(i);
pw.println(bookmark.getTitle() + "\n" + bookmark.getUrl() + "\n" + bookmark.getNote());
}
pw.close();
} catch (FileNotFoundException e) {
Log.e("Write ERR", "Cannot save: " + e.getMessage());
e.printStackTrace();
Toast.makeText(BookNote.this, "Error saving", Toast.LENGTH_SHORT).show();
}
}
//If addBookmark menu item is clicked, this will be called to add a bookmark to the end of the ArrayAdapter.
private void addBookmark(Bookmark bookmark){
adapter.add(bookmark);
writeData();
}
//Calls ManageActivity and reports information about app.
public void gotoManageActivity(boolean addBookmarkClicked){
Intent manageIntent = new Intent(this, ManageActivity.class);
Bundle extras = new Bundle();
extras.putString("bookmark", bookmarkClicked);
extras.putBoolean("addBookmarkClicked", addBookmarkClicked);
extras.putInt("listViewID", listViewID);
manageIntent.putExtras(extras);
startActivity(manageIntent);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_add) {
addBookmarkClicked = true;
gotoManageActivity(addBookmarkClicked);
return true;
}
return super.onOptionsItemSelected(item);
}
}
ManageActivity
public class ManageActivity extends AppCompatActivity {
private String title = "EMPTY", url = "EMPTY", note = "EMPTY";
private boolean listener = true;
private boolean addBookmarkClicked = false;
/* When activity starts, check for addBookmarkClicked status, create book */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_layout);
addBookmarkClicked = getIntent().getExtras().getBoolean("addBookmarkClicked", false);
String bookmarkString = "";
bookmarkString = getIntent().getExtras().getString("bookmark");
if(bookmarkString != null && bookmarkString.length() > 0) {
if (bookmarkString.length() != 0) {
String[] stringArray = bookmarkString.split("\\n");
title = stringArray[0];
url = stringArray[1];
note = stringArray[2];
updateTextViews();
}
}
else { updateTextViews();
}
}
#Override
public void onBackPressed(){
Intent bookNoteIntent = new Intent(this, BookNote.class);
Bundle extras = new Bundle();
if(title.length() == 0 || title == null){title= "Empty";}
if(url.length() == 0 || url == null){ url = "Empty";}
if(note.length() == 0 || url == null) { note = "Empty";}
extras.putString("title", title);
extras.putString("url", url);
extras.putString("note", note);
extras.putBoolean("listen", listener);
extras.putBoolean("addBookmarkClicked", addBookmarkClicked);
bookNoteIntent.putExtras(extras);
startActivity(bookNoteIntent);
}
Great question! I had to deal with this issue myself as well, a couple of weeks ago.
The main thing is that you will need to re-instantiate your ArrayAdapter, or adapter in your case.
Now you do the first step correctly:
bookmarkList = readData();
adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);
setListAdapter(adapter);
But you will do this again when trying to update the list: I believe you added the new bookmark correctly, but you'll need to re-create the ArrayAdapter for the listview.
EDIT:
I believe I found the peril.
Right here you will need to re-instantiate the ArrayAdapter, as I mentioned earlier.
private void addBookmark(Bookmark bookmark){
adapter.add(bookmark);
writeData();
}
Basically, whenever you update the data to be shown in your list, you need to do this step...
I solved the issue for "checking if location is enabled", but now I'm stuck. I want the app to show a toast if location is disabled, and once it's enabled by the user, I want the app to proceed as normal, like location was enabled at the first place. My code looks correct to me, I don't know where the problem is. Note that I don't have any issues with accessing the location, network and stuff. It's just that I always need to restart the app after enabling location, otherwise it won't proceed and keep giving me the warning toast. Thanks in advance.
Edit: So I just added an alert dialog method instead of Toast messages. Users can now go to settings and turn location and network on using that dialog. I'd like you to take a look at the Network check if-else statement inside getForecast() method. else contains the alert dialog that leads user to Settings-Data Roaming. And when user activated mobile data and returns to the app, everything's fine and app can get info. I did the same for location if-else statement, yet when user turns location on and returns to the app, no matter what I do (wait several minutes, refresh several times), I'm not getting the location info. I need to close and reopen the app every time. That's the exact issue I'm facing.
Code:
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
public static final String DAILY_FORECAST = "DAILY_FORECAST";
private Forecast mForecast;
#Bind(R.id.timeLabel) TextView mTimeLabel;
#Bind(R.id.tempLabel) TextView mTempLabel;
#Bind(R.id.humidityValue) TextView mHumidityValue;
#Bind(R.id.precipValue) TextView mPrecipValue;
#Bind(R.id.summaryLabel) TextView mSummaryLabel;
#Bind(R.id.windSpeedValue) TextView mWindSpeedValue;
#Bind(R.id.relativeLayout) RelativeLayout mRelativeLayout;
#Bind(R.id.container) SwipeRefreshLayout mSwipeRefreshLayout;
#Bind(R.id.locationLabel) TextView mLocationLabel;
double latitude;
double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
final GPSTracker gpsTracker = new GPSTracker(this);
mSwipeRefreshLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(false);
}
}, 1500);
if (gpsTracker.getIsGPSTrackingEnabled()){
getForecast(gpsTracker);
updateDisplay(gpsTracker);
} else {
Toast.makeText(MainActivity.this, "Please enable location services.!!", Toast.LENGTH_LONG).show();
gpsTracker.showSettingsAlert();
}
}
});
getForecast(gpsTracker);
}
private void getForecast(final GPSTracker gpsTracker) {
latitude = gpsTracker.getLatitude();
longitude = gpsTracker.getLongitude();
String apiKey = "7d22cdb138cd70f2e9e8d2006cd0461c";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey
+ "/" + latitude + "," + longitude;
if (isNetworkAvailable()) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(forecastUrl).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mForecast = parseForecastDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
if (gpsTracker.getIsGPSTrackingEnabled()) {
updateDisplay(gpsTracker);
} else {
Toast.makeText(MainActivity.this, "Please enable location services.", Toast.LENGTH_LONG).show();
}
}
});
} else {
alertUserAboutError();
}
} catch (IOException | JSONException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
} else {
gpsTracker.showSettingsAlert2();
}
}
private void updateDisplay(GPSTracker gpsTracker) {
Currently currently = mForecast.getCurrently();
String area = gpsTracker.getSubLocality(this);
String city = gpsTracker.getAdminArea(this);
String country = gpsTracker.getCountryName(this);
mLocationLabel.setText(area + "\n" + city + ", " + country);
mTempLabel.setText(currently.getTemperature() + "");
mTimeLabel.setText(currently.getFormattedTime());
mHumidityValue.setText(currently.getHumidity() + "%");
mPrecipValue.setText(currently.getPrecipChance() + "%");
mSummaryLabel.setText(currently.getSummary());
mWindSpeedValue.setText(currently.getWindSpeed() + "");
Drawable drawable = getResources().getDrawable(currently.getBackgroundId());
mRelativeLayout.setBackground(drawable);
}
// irrelevant after this point. (I guess)
private Forecast parseForecastDetails(String jsonData) throws JSONException {
Forecast forecast = new Forecast();
forecast.setCurrently(getCurrentlyDetails(jsonData));
forecast.setHourlyForecast(getHourlyForecast(jsonData));
forecast.setDailyForecast(getDailyForecast(jsonData));
return forecast;
}
private Daily[] getDailyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject jsonDaily = forecast.getJSONObject("daily");
JSONArray data = jsonDaily.getJSONArray("data");
Daily[] days = new Daily[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject daily = data.getJSONObject(i);
Daily day = new Daily();
day.setSummary(daily.getString("summary"));
day.setTempMax(daily.getDouble("temperatureMax"));
day.setTempMin(daily.getDouble("temperatureMin"));
day.setIcon(daily.getString("icon"));
day.setTime(daily.getLong("time"));
day.setTimezone(timezone);
days[i] = day;
}
return days;
}
private Hourly[] getHourlyForecast(String jsonData) throws JSONException{
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject jsonHourly = forecast.getJSONObject("hourly");
JSONArray data = jsonHourly.getJSONArray("data");
Hourly[] hours = new Hourly[data.length()];
for(int i=0; i < data.length(); i++) {
JSONObject hourly = data.getJSONObject(i);
Hourly hour = new Hourly();
hour.setSummary(hourly.getString("summary"));
hour.setTemp(hourly.getDouble("temperature"));
hour.setIcon(hourly.getString("icon"));
hour.setTime(hourly.getLong("time"));
hour.setTimezone(timezone);
hours[i] = hour;
}
return hours;
}
private Currently getCurrentlyDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject currently = forecast.getJSONObject("currently");
Currently currentWeather = new Currently();
currentWeather.setHumidity(currently.getDouble("humidity"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
currentWeather.setSummary(currently.getString("summary"));
currentWeather.setTemperature(currently.getDouble("temperature"));
currentWeather.setWindSpeed(currently.getDouble("windSpeed"));
currentWeather.setTimeZone(timezone);
currentWeather.setBackgroundId(currently.getString("icon"));
Log.d(TAG, currentWeather.getFormattedTime());
return currentWeather;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()){
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
#OnClick (R.id.dailyButton)
public void startDailyActivity(View view){
Intent intent = new Intent(this, DailyForecastActivity.class);
intent.putExtra(DAILY_FORECAST, mForecast.getDailyForecast());
startActivity(intent);
}
}