I want to make my own library for getting the weather. I made the same in MainActivity and it works but when a put the same method in an another Class java i get error with Tosts and getApplicationContext methods. How can i fix it
public class WeatherClass {
public static void getCurrentWeather(String location) {
final String[] urlCityGetTemperature = {"https://www.metaweather.com/api/location/"};
String urlCityGetId = "https://www.metaweather.com/api/location/search/?query=";
final String[] finishUrl = new String[1];
String tempUrl = "";
String city = "";
city = location;
if(city.equals("")) {
//тут пишем код, если ползователь ничего не ввел в поле и нажал на кнопку
}
else {
tempUrl = urlCityGetId + city;
String finalCity = city;
StringRequest stringRequest = new StringRequest(Request.Method.GET, tempUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
String output = "";
try {
JSONArray jsonResponce = new JSONArray(response);
if(response.equals("[]")) {
//уведомление о неккоректном вводе названия города
}
JSONObject jsonObjectZeroIndex = jsonResponce.getJSONObject(0);
int woeid = jsonObjectZeroIndex.getInt("woeid");
//tvRes.setText(output);
finishUrl[0] = urlCityGetTemperature[0] + output;
//тут мы будем получат температуру по id города.
StringRequest stringRequestGetTeperatureWithId = new StringRequest(Request.Method.GET, finishUrl[0], new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("finalLink", response);
String outputTemp = "";
String outPutWeather;
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("consolidated_weather");
JSONObject jsonObectFromArray = jsonArray.getJSONObject(0);
int woeid = jsonObectFromArray.getInt("the_temp");
outputTemp = String.valueOf(woeid);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext);
requestQueue.add(stringRequestGetTeperatureWithId);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext);
requestQueue.add(stringRequest);
}
}
}
getApplicationContext and Toasts doesn't work.
You can pass second parameter Context to getCurrentWeather, and then pass that context to The Toast.
Here is getCurrentWeather Method inside WeatherClass Like This,
public class WeatherClass {
public static void getCurrentWeather(String location,Context context){
// Here is your fetch whether code
// Your Toast like this
Toast.makeText(context,"Your Message", Toast.LENGTH_SHORT).show();
}
}
When you call this method from MainActivity, call Method like this,
getCurrentWeather(location,getApplicationContext())
Related
I"m populating the listview from online using JSON. It works great...But I wanted to implement method of SwipeRefresh layout such that old data will be replace with new one in every Swipe user make.
Instead of clearing old data with new one, Everytime on SwipeRefresh new data is added at the bottom of old data.
I also set notifysetAdapter; but it doesn't seems to work.
Here is my code
mSwipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
mExampleList.clear();
mExampleAdapter.notifyDataSetChanged();
parseJSON();
}
}
);
}
}
private void parseJSON() {
String url = getIntent().getStringExtra(EXTRA_URL);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
myProgressBar.setVisibility(View.GONE);
try {
JSONArray jsonArray = response.getJSONArray("hits");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String videoTitle = hit.getString("title");
String link = hit.getString("link");
// String notes = hit.getString("notes");
// String question = hit.getString("question");
// String imageUrl = hit.getString("webformatURL");
// int likeCount = hit.getInt("likes");
mExampleList.add(new ExampleItem(videoTitle,link));
mExampleAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
mSwipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
mSwipeRefreshLayout.setRefreshing(false);
}
});
mRequestQueue.add(request);
}
I need help to solve this.
Use setOnRefreshListener
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
parseJSON();
// just on refresh call parseJSON method
}
});
Clear data in parseJSON method before add new data, and set notifyDataSetChanged out for loop.
private void parseJSON() {
String url = getIntent().getStringExtra(EXTRA_URL);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
myProgressBar.setVisibility(View.GONE);
try {
mExampleList.clear();
JSONArray jsonArray = response.getJSONArray("hits");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String videoTitle = hit.getString("title");
String link = hit.getString("link");
// String notes = hit.getString("notes");
// String question = hit.getString("question");
// String imageUrl = hit.getString("webformatURL");
// int likeCount = hit.getInt("likes");
mExampleList.add(new ExampleItem(videoTitle,link));
}
mExampleAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
mSwipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
mSwipeRefreshLayout.setRefreshing(false);
}
});
mRequestQueue.add(request);
}
I have an app where I use the info provided by the user to get a list of data
Using the code below, I'm getting two different results:
When where username = '$username' is presented on the PHP side, I receive just the Toast message. However, ListView remains empty.
When I remove where username = '$username' from PHP side, Toast message is displayed and the ListView also shows some content
Could you please help me to undestand why the ListView remains empty on that specific case?
Thanks in advance
Java
public void current_user() {
String url = "http://websie/my.php";
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dayes = new SimpleDateFormat("dd-MM-yyyy");
final String created_date = dayes.format(calendar.getTime());
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//System.out.println(response);
// Toast.makeText(MainActivity.this,response,Toast.LENGTH_SHORT).show();
Toast.makeText(show_post_all_sales_2x100.this, response.toString(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
listViewAdapter = new ListViewAdapter(show_post_all_sales_2x100.this, R.layout.listview_items_layout, SubjectList);
listView.setAdapter(listViewAdapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(show_post_all_sales_2x100.this, error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username", User.getUsername());
params.put("created_date", created_date);
return params;
}
};
RequestQueue requestQueue = com.android.volley.toolbox.Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
public ParseJSonDataClass(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpParseClass httpParseClass = new HttpParseClass(HttpURL);
try {
httpParseClass.ExecutePostRequest();
if (httpParseClass.getResponseCode() == 200) {
FinalJSonResult = httpParseClass.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Subjects subjects;
SubjectList = new ArrayList<Subjects>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
String tempName = jsonObject.getString("username").toString();
String tempFullForm = jsonObject.getString("created_date").toString();
subjects = new Subjects(tempName, tempFullForm);
SubjectList.add(subjects);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
Toast.makeText(context, httpParseClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
progressBar.setVisibility(View.INVISIBLE);
listViewAdapter = new ListViewAdapter(show_post_all_sales_2x100.this, R.layout.listview_items_layout, SubjectList);
listView.setAdapter(listViewAdapter);
}
}
PHP
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'DatabaseConfig.php';
$username = $_POST['username'];
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM post_2x where username = '$username'" ;
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
}
?>
Result when where username = '$username' is present
Result when I remove where username = '$username'
I'm trying to handle this null exception in RecyclerView from PHP URL. I want it to show a Toast message if a null exception occurs: No Result Found.
null exception:
Code
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray(uarray);
for (int i = 0; i < array.length(); i++) {
JSONObject p = array.getJSONObject(i);
Category_Movie item = new Category_Movie(
p.getInt("id"),
p.getString("mTitle"),
p.getString("mDesc"),
p.getInt("mYear"),
);
listItems.add(item);
}
mAdapter = new CategoryListAll_Adapter(listItems, getActivity());
recyclerView.setAdapter(mAdapter);
} catch(JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
EDIT
Create one method to validate your JSONObject
public boolean isJSONValid(String jsonStr) {
try {
new JSONObject(jsonStr);
} catch (JSONException ex) {
return false;
}
return true;
}
Try to edit following code:
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (isJSONValid(response)) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray(uarray);
for (int i = 0; i < array.length(); i++) {
JSONObject p = array.getJSONObject(i);
Category_Movie item = new Category_Movie(
p.getInt("id"),
p.getString("mTitle"),
p.getString("mDesc"),
p.getInt("mYear"),
);
listItems.add(item);
}
mAdapter = new CategoryListAll_Adapter(listItems, getActivity());
recyclerView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
// your Toast Message
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
Returning early ordinary is way to go ...
therefore I'd compare to the known String value of null, in case of no results,
before checking if it possibly could be valid JSON (which can already be out-ruled):
if(! response.equals("null")) {
try ...
}
or improve statement e.printStackTrace() and handle that JSONException accordingly:
try {
...
} catch(JSONException e) {
if(response.equals("null")) {
/* assume no results */
} else {
e.printStackTrace();
}
}
While having access to the PHP code ...better always return a parse-able JSON response:
header("Content-Type: application/json");
die(json_encode((object) array(
"success" => false,
"error" => "no results"
)));
... when the client expects application/json instead of text/plain.
I am developing an app for Downloading Images and their Description from Flickr.
I am setting Description String into GetterAndSetter Class's ArrayList and when i want to fetch the Data from that class,
even logger not Printing. And so that when i tried to set the values from stringArray onto the UI, I am getting ArrayIndexoutofBound Exception.
My Code is Following :
#Override
protected void onCreate(Bundle savedInstanceState) {
...
LoadImages(this);
...
}
My LoadImages Method :
private void LoadImages(MainActivity mainActivity) {
if (checkInternet()) {
StringRequest stringRequest = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Respone", "onResponse: " + response);
// Used to Get List of Images URLs
getResponse = ParseJSON(response);
List<String> urlList = getResponse.get(0);
List<String> titles = getResponse.get(1);
// Getting String Array from GetterAndSetter Class...
// Not Properly Getting from there...
List<String> Details = getterAndSetter.getStringList();
// Printing Check
for (String urls:urlList) {
Log.d("urls", urls);
}
// Printing Check
for (String title:titles) {
Log.d("titles", title);
}
// Problem is here, Not Getting
**This is not even Executing...**
for (String str: Details) {
Log.d("GetDetails", str);
}
...
}
}, error -> {
Log.d(TAG, "onErrorResponse: Error Occured...");
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
mView.show(getSupportFragmentManager(), "Loading...");
} else {
Toast.makeText(this, "Turn Internet on...", Toast.LENGTH_SHORT).show();
}
}
My ParseJSON method :
ArrayList<ArrayList<String>> ParseJSON(String URL) {
try {
...
ArrayList<String> listURLS = new ArrayList<>();
ArrayList<String> Titles = new ArrayList<>();
ArrayList<ArrayList<String>> result = new ArrayList<>();
for (int i = 0; i < photo.length(); i++) {
JSONObject photosJSONObject = photo.getJSONObject(i);
String FarmID = photosJSONObject.getString("farm");
String ServerID = photosJSONObject.getString("server");
String ID = photosJSONObject.getString("id");
String SecretID = photosJSONObject.getString("secret");
String ImageTitle = photosJSONObject.getString("title");
listURLS.add(i, CreatePhotoURL(FarmID, ServerID, ID, SecretID));
Titles.add(i, ImageTitle);
String CreateURL = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=" + API_Key + "&photo_id=" + ID + "&format=json&nojsoncallback=1";
AddtoList(CreateURL);
result.add(listURLS);
result.add(Titles);
}
return result;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
My AddtoList Method :
public void AddtoList(String CreateURL) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(CreateURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Desc", response);
JSONObject root = null;
try {
root = new JSONObject(response);
JSONObject photo = root.getJSONObject("photo");
String username = photo.getJSONObject("owner").getString("username");
String DateTaken = photo.getJSONObject("dates").getString("taken");
String Views = photo.getString("views");
String FormattedStr = "Date Taken : " + DateTaken + "\n" + "Views : " + Views + "\n" + "User Name : " + username + "\n";
// Properly Working...
Log.d("Describe", FormattedStr);
// I cant say about this...
getterAndSetter.getStringList().add(FormattedStr);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse: " + error.toString());
}
});
requestQueue.add(stringRequest);
}
My GetterAndSetter Class :
public final class GetterAndSetter {
private final ArrayList<String> stringList = new ArrayList<>();
public ArrayList<String> getStringList() {
return stringList;
}}
I am working on a project and below my code basically takes an array of objects and sets the Id to each object, However, when I click on my objects I would like to get that Id. I tried a local variable and I could only get the Id of the last object, how do I do this? I would like to get the value of String Answerid = currentQuestions.getString("id"); into my OnDown clicklistener.
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_ANSWER, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listblogs = parseJSONResponseQuestion(response);
mAdapterQuestion.setBloglist(listblogs);
System.out.println(response);
System.out.println("it worked!!!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
});
mRequestQueue.add(request);
}
String globalVar = " ";
private ArrayList<Blogs> parseJSONResponseQuestion(JSONArray response) {
if (!response.equals("")) {
ArrayList<Blogs> blogsArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String questionId = currentQuestions.getString("questionId");
String votes = currentQuestions.getString("votes");
String Answerid = currentQuestions.getString("id");
System.out.println(response.length() + "length");
data.append(text + Answerid + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setMtext(text);
blogs.setVotes(votes);
blogs.setId(Answerid);
System.out.print(Answerid);
listblogs.add(blogs);
}
System.out.println(data.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
public void OnDown(View view) {
System.out.println("VOTED Down");
final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();
final String PUT_VOTE_UP = "someURL";
StringRequest PostVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_UP, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response + "reponse");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println("************Answer" + error + "error");
}
});
mrequestQueue.add(PostVoteUp);
System.out.println("VOTED DOWN");
}
}
Your click listener OnDown(View view) gets a view that was clicked. That's the only way you can identify what was clicked.
You should use View.getTag() to get the id:
Object obj = view.getTag();
The question is where can you add this code to set it:
View view = ...; // new View()?
view.setTag(object);