Every time I run this code, I get the message "File not found" in my exception however, I don't understand why is that when I literally have the file I'm looking for sitting at the root of my c:?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView testMEtext = (TextView) findViewById(R.id.testMEtext);
//
JSONParser parser = new JSONParser();
try {
//File temp = new File("C:/Windows/outdoorWeather.json");
//String path = temp.getAbsolutePath();
//testMEtext.setText(path);
**Object obj = parser.parse(new FileReader("/C:/outdoorWeather.json"));**
JSONObject jsonObject = (JSONObject) obj;
String oTemp = (String) jsonObject.get("Fahrenheit temperature");
testMEtext.setText(oTemp);
}
catch (FileNotFoundException e) {
e.printStackTrace();
testMEtext.setText("File not found");
}
catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
I don't think you can interact with objects outside of your emulator. To solve it try referring to these.
Load a simple text file in android studio
How can I read a text file in android
Reading a simple text file
Related
I have a web application (Maven project, JSP/SERVLET, TomCat 8.5.20). The application run perfectly in localhost (same TomCat version), but when i deploy to a live server, the following code doesn't work, the 'x01Json' (JSONObject) variable value be 'null' after i cal the transfromGameToJson() method.
Game init servlet, where i set JSON in request
X01Game x01Game = gameController.initX01Game(type, legsNumber, setsNumber, users, doubleIn, doubleOut, x01,
randomOrder, startingPoint);
JSONObject x01Json = gameController.transfromGameToJson(x01Game);
session.setAttribute("x01Game", x01Game);
request.setAttribute("x01Json", x01Json);
request.getRequestDispatcher("/darts/x01game.jsp").forward(request, response);
the method
public JSONObject transfromGameToJson(X01Game x01Game) {
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(new File("x01Game.json"), x01Game);
JSONObject object = new JSONObject(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(x01Game));
return object;
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
If i delete this line from my method, it's working:
mapper.writeValue(new File("x01Game.json"), x01Game);
Every time I open my app it crashes because of this error I dont know what should I do please help me... I have also attached logcat screen shot below and the java class in which the error is comming.
DataParser.java:
public class DataParser {
private HashMap<String,String> getPlace(JSONObject googlePlacesJson){
HashMap<String,String> googlePlaceMap=new HashMap<>();
String placeName="-NA-";
String vicinity="-NA-";
String latitude="";
String logitude="";
String reference="";
List<HashMap<String,String>> placesList=new ArrayList<>();
try {
if(!googlePlacesJson.isNull("name")){
placeName=googlePlacesJson.getString("name");
}
if (!googlePlacesJson.isNull("vicinity")){
vicinity=googlePlacesJson.getString("vicinity");
}
latitude=googlePlacesJson.getJSONObject("geometry").getJSONObject("location").getString("lat");
logitude=googlePlacesJson.getJSONObject("geometry").getJSONObject("location").getString("lng");
reference=googlePlacesJson.getString("reference");
googlePlaceMap.put("name",placeName);
googlePlaceMap.put("vicinity",vicinity);
googlePlaceMap.put("lat",latitude);
googlePlaceMap.put("lng",logitude);
googlePlaceMap.put("reference",reference);
} catch (JSONException e) {
e.printStackTrace();
}
return googlePlaceMap;
}
private List<HashMap<String,String>> getPlaces(JSONArray jsonArray){
long count;
count=jsonArray.length(); // error comes on this line
List<HashMap<String,String>> placesList=new ArrayList<>();
HashMap<String,String> placeMap=null;
for(int i=0;i<count;i++){
try {
placeMap=getPlace((JSONObject) jsonArray.get(i));
placesList.add(placeMap);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
public List<HashMap<String,String>> parse(String jsonData){
JSONArray jsonArray=null;
JSONObject jsonObject;
try {
jsonObject=new JSONObject(jsonData);
jsonArray=jsonObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
return getPlaces(jsonArray);
}
}
this is the screen shot my my log cat:
The problem is somewhere in here:
public List<HashMap<String,String>> parse(String jsonData){
JSONArray jsonArray=null;
JSONObject jsonObject;
try {
jsonObject=new JSONObject(jsonData);
jsonArray=jsonObject.getJSONArray("results"); // !!! this line here !!!
} catch (JSONException e) {
e.printStackTrace();
}
return getPlaces(jsonArray);
}
getJSONArray("results"); returns null and that's causing problems later (NullPointerException).
What you should do:
Check your JSON for syntax errors.
Place a breakpoint at the getJSONArray() line and take a look at jsonData and jsonObject if everything is, as it should be.
The array you want to retrieve is probably not valid or not in the jsonData at all.
i would start by validating if the jsonArray is null before running the entire method. or:
if (jsonArray != null)
count=jsonArray.length();
else count = 0;
then debug to find out why you are calling that method with a null object.
I have to add result at the last column of each row. I have to test user successfully login with correct email and password the "PASS" is append to last else "FAIL" and go with the second row and check the result of each row.
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Selenium Drivers\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://www.facebook.com");
// This will load csv file
CSVReader reader = null;
try{
reader = new CSVReader(new FileReader("C:\\Users\\src\\com\\elements\\demo.csv"));
}catch (Exception e) {
e.printStackTrace();
}
String[] cell;
while ((cell=reader.readNext())!=null){
for(int i=0;i<1;i++){
String emailid=cell[i];
String password=cell[i+1];
driver.findElement(By.id("email")).sendKeys(emailid);
driver.findElement(By.id("pass")).sendKeys(password);
driver.findElement(By.id("loginbutton")).click();
String outputFile = "C:\\Users\\src\\com\\elements\\demo.csv";
try {
// use FileWriter constructor that specifies open for appending
CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true),',');
if(driver.getTitle().equals("Log1 in to Facebook | Facebook"))
{
csvOutput.write("Pass"); //Your selenium result.
//csvOutput.endRecord();
//csvOutput.close();
}
else if (driver.getTitle().equals("Log in to Facebook | Facebook"))
{
csvOutput.write("userName");
csvOutput.write("password");
csvOutput.write("Fail"); //Your selenium result.
csvOutput.endRecord();
csvOutput.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Try this code.
String outputFile = "test.csv";
// before we open the file check to see if it already exists
boolean alreadyExists = new File(outputFile).exists();
try {
// use FileWriter constructor that specifies open for appending
CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true),',');
// if the file didn't already exist then we need to write out the header line
if (!alreadyExists){
csvOutput.write("result");
csvOutput.endRecord();
}
// else assume that the file already has the correct header line
// write out a few records
csvOutput.write("userName");
csvOutput.write("password");
csvOutput.write("Pass/Fail"); //Your selenium result.
csvOutput.endRecord();
csvOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
OR
If we want to use writeNext() method which take string array as a parameter then
String csv = "D:\\test.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
List<String[]> data = new ArrayList<String[]>();
data.add(new String[] {"India", "New Delhi"});
data.add(new String[] {"United States", "Washington D.C"});
data.add(new String[] {"Germany", "Berlin"});
writer.writeAll(data);
writer.close();
Try other option.
FileWriter writer = new FileWriter("D:/test.csv",false);
writer.append(" ");
writer.append(',');
writer.append("UserName");
writer.append(',');
writer.append("Password");
writer.append(',');
writer.append("Pass/Fail");
writer.append('\n');
//generate whatever data you want
writer.flush();
writer.close();
Can anyone can show me, with sample codes:
How to post JSON to a REST webservice; and
How to read the JSON response from the server;
Using Codename One?
Here is what i have tried which is returning bad request response from the server:
Button b1 = new Button("Add Staff");
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
JSONObject json = new JSONObject();
try {
ConnectionRequest post = new ConnectionRequest(){
#Override
protected void postResponse() {
try {
json.put("firstname", fname.getText());
json.put("middlename", mname.getText());
json.put("lastname", lname.getText());
json.put("dob", dob.getText());
json.put("gender", gender.getSelectedItem().toString());
json.put("marital", marital.getSelectedItem().toString());
json.put("phone", phone.getText());
json.put("adds", adds.getText());
json.put("username", user.getText());
json.put("password", pass.getText());
json.put("lat", lat.getText());
json.put("long", lon.getText());
} catch (JSONException ex) {
ex.printStackTrace();
}
}
#Override
protected void readResponse(InputStream input) throws IOException {
}
};
post.setUrl("http://localhost:8093/halimatbank/cbs/staff");
post.setPost(true);
post.setContentType("APPLICATION/JSON");
post.addArgument("body", json.toString());
boolean show = Dialog.show("Add Staff", "Are you Sure you want to add this Staff", "Yes", "NO");
NetworkManager.getInstance().addToQueueAndWait(post);
Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(post.getResponseData()), "UTF-8"));
Map<String, Object> response = (Map<String, Object>)result.get("response");
Dialog.show("Staff Saved", ""+response, "OK","");
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
postResponse() is invoked after the process completes. Not related to post itself. You want to override buildRequestBody which executes before. If I understand correctly you want the entire body to be the JSON and not an argument named "body" which is what you did...:
ConnectionRequest post = new ConnectionRequest(){
#Override
protected void buildRequestBody(OutputStream os) throws IOException {
os.write(json.toString().getBytes("UTF-8"));
}
#Override
protected void readResponse(InputStream input) throws IOException {
// parse response data
}
};
post.setUrl("http://localhost:8093/halimatbank/cbs/staff");
post.setPost(true);
post.setContentType("application/json");
I'm developing an Android App and i create a slide menu. In the slide menu i have item "Search". This is a fragment that call a json (using volley) and input the result into custom list view.
Now when i call the fragment (using debug mode) the fragment start to download some data but after some record of json download the app crash and i receive this error:
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.firstproject.fragment.SearchFragment.loadListView(SearchFragment.java:175)
at com.firstproject.fragment.SearchFragment.access$000(SearchFragment.java:46)
at com.firstproject.fragment.SearchFragment$1.onResponse(SearchFragment.java:105)
at com.firstproject.fragment.SearchFragment$1.onResponse(SearchFragment.java:98)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
I attach my code where i call a json file (for privacy delete the url json)
Any help please?
Thanks
public class SearchFragment extends Fragment {
public SearchFragment(){}
private static final String url = "http://<server_name>/<folder>/data.json";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_search, container, false);
}
ListView geoJSON;
String globalResponse="";
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String tag_string_req = "string_req";
final ProgressDialog pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
RequestQueue mRequestQueue;
Network network = new BasicNetwork(new HurlStack());
//Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Instantiate the RequestQueue with the cache and network.
Cache cache = AppController.getInstance().getRequestQueue().getCache();
mRequestQueue = new RequestQueue(cache, network);
// Start the queue
mRequestQueue.start();
Cache.Entry entry = cache.get(url);
if(entry != null){
try {
String data = new String(entry.data, "UTF-8");
//loadListView(gobalResponse,0,1000);
//Toast.makeText(getActivity(), "Cache utilized!", 0).show();
// handle data, like converting it to xml, json, bitmap etc.,
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}else{
// Cached response doesn't exists. Make network call here
StringRequest strReq = new StringRequest(Request.Method.GET,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
globalResponse=response;
Globals.GlobalResponse=globalResponse;
Log.d("", response.toString());
loadListView(globalResponse,0,1000);
//loadListView(response,0,1000);
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
//Toast.makeText(getApplicationContext(), error.getMessage()+"", 0).show();
pDialog.hide();
}
});
strReq.setShouldCache(true);
//strReq.
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
private ArrayList<GeoJsonResponse> globalResponseObject;//=new ArrayList<GeoJsonResposne>();
private void loadListView(String response,float lowerLimit,float upperLimit)
{
try {
JSONObject featureCollection=new JSONObject(response);
globalResponseObject=new ArrayList<GeoJsonResponse>();
JSONArray features=featureCollection.getJSONArray("features");
for (int i = 0; i < features.length(); i++) {
JSONObject properties=features.getJSONObject(i);
float mag=Float.parseFloat(properties.getJSONObject("properties").getString("mag"));
if(!(mag>=lowerLimit&&mag<upperLimit)) continue;
Log.d("",properties.getJSONObject("properties").getString("author")
+ properties.getJSONObject("properties").getString("mag")
+ properties.getJSONObject("properties").getString("place")
+ properties.getJSONObject("geometry").getJSONArray("coordinates").getString(0)
+ properties.getJSONObject("geometry").getJSONArray("coordinates").getString(1)
+ properties.getJSONObject("geometry").getJSONArray("coordinates").getString(2)
);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date1 = format.parse(properties.getJSONObject("properties").getString("time"));
GeoJsonResponse obj=new GeoJsonResponse(
properties.getJSONObject("properties").getString("eventId"),
properties.getJSONObject("properties").getString("author"),
properties.getJSONObject("properties").getString("place"),
Double.parseDouble(properties.getJSONObject("properties").getString("mag")),
Double.parseDouble(properties.getJSONObject("geometry").getJSONArray("coordinates").getString(2)),
properties.getJSONObject("properties").getString("time"),date1,
Double.parseDouble(properties.getJSONObject("geometry").getJSONArray("coordinates").getString(0)),
Double.parseDouble(properties.getJSONObject("geometry").getJSONArray("coordinates").getString(1))
);
globalResponseObject.add(obj);}
if(lowerLimit==0)
Globals.geoJsonResponse=globalResponseObject;
// Collections.sort(globalResponseObject, new DateSorter());
CustomListAdapter adpater=new CustomListAdapter(getActivity()
, globalResponseObject);
adpater.notifyDataSetChanged();
geoJSON.setAdapter(adpater);
geoJSON.invalidate();
geoJSON.invalidateViews();
//, author, place, magnitude, distance, date)
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}