How to input text from edit text in json array - android

i'm new to android json and just starting working on it as in place of sqllite databse ,
i want user to input data into edit text and it go and save into the json array like we use to do in the sqllite databse by table
queryValues.put("studentid", studentId);
queryValues.put("roll", roll.getText().toString());
queryValues.put("name", name.getText().toString());
queryValues.put("class", Class.getText().toString());
queryValues.put("marks", marks.getText().toString());
data.updatestudent(queryValues);
so is there any way that we can make user to input data from edit text and then it go save into json Array and also user can do update and delete operations.
or if there is anyother way , guide me into that direction .
Also i can't find any good example of json .

yes you can ,
on button click you have to retrieve all values from editext ,
make a jsonobject like that
JSONObject student1 = new JSONObject();
try {
student1.put("id", "3");
student1.put("name", "NAME OF STUDENT");
student1.put("year", "3rd");
student1.put("curriculum", "Arts");
student1.put("birthday", "5/5/1993");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Try it this way:
Before you make a call to the below function, make sure that your edit text does not return null. Use basic validations.
public JSONArray makeJSON() {
JSONArray jArr = new JSONArray();
JSONObject jObj = new JSONObject();
try {
jObj.put("customer_name", edittex1.getText().toString);
jObj.put("serial_number", edittex2.getText().toString);
jObj.put("membership_number", edittex3.getText().toString);
jObj.put("brand_name", edittex4.getText().toString);
jObj.put("model_number", edittex5.getText().toString);
jObj.put("IMEI_number", edittex6.getText().toString);
jObj.put("handset_purchase", edittex7.getText().toString);
jObj.put("counter_name", edittex8.getText().toString);
jArr.put(jObj);
} catch (Exception e) {
System.out.println("Error:" + e);
}
return jArr;
}

[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/7dR28.png
Facing error as mentioned inside the image:
JSONArray Tracelists = null;
for (int i = 0; i < GetDataAdapter1.size(); i++) {
Tracelists = new JSONArray();
JSONObject Tracelist = new JSONObject();
try {
if (GetDataAdapter1.get(i).getEditTextValue().equalsIgnoreCase("")) {
flag = "NA";
} else {
flag = GetDataAdapter1.get(i).getEditTextValue();
}
Tracelist.put("TRACEEditTextValue", flag);
Tracelist.put("CODE", GetDataAdapter1.get(i).getCODE());
Tracelists.put(Tracelist);
Log.d("tracevalues2-", "onClick: " + Tracelists);
} catch (JSONException e) {
e.printStackTrace();
System.out.println("Error:" + e);
}
// btnnext.setText("," + GetDataAdapter1.get(i).getEditTextValue() + System.getProperty("line.separator"));
}

Related

How to write to existing JSON file?

I need some help in writing to an existing json file. I can parse the data and read from it using GSON or just json in this example. I did it this way to filter the results by id displayed on screen. So it grabs the add and searches my list of over 900 videos and then gives the ones selected. Only issue is i don't want to display them i want to save them :)
final Button button = findViewById(R.id.buttonx);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// load json parse json and grab fields...
// then write to new file!
try {
//Load File
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(getResources().openRawResource(R.raw.movielist)));
StringBuilder jsonBuilder = new StringBuilder();
for (String line = null; (line = jsonReader.readLine()) != null;) {
jsonBuilder.append(line).append("\n");
}
//Parse Json
JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
JSONArray jsonArray = new JSONArray(tokener);
ArrayList<String> fields = new ArrayList<String>();
for (int index = 0; index < jsonArray.length(); index++) {
//Set both values into the listview
JSONObject jsonObject = jsonArray.getJSONObject(index);
String series = jsonObject.getString("id");
if (series.equals(tvId.getText())) {
fields.add(jsonObject.getString("movie"));
fields.add(jsonObject.getString("year"));
fields.add(jsonObject.getString("duration"));
fields.add(jsonObject.getString("director"));
fields.add(jsonObject.getString("image"));
fields.add(jsonObject.getString("id"));
}
}
} catch (FileNotFoundException e) {
Log.e("jsonFile", "file not found");
} catch (IOException e) {
Log.e("jsonFile", "ioerror");
} catch (JSONException e) {
Log.e("jsonFile", "error while parsing json");
}
Toast.makeText(DetailActivity.this, "The following movie has been saved " + tvId.getText(), Toast.LENGTH_LONG).show();
// Toast.makeText(DetailActivity.this, "This features is not working", Toast.LENGTH_LONG).show();
}
});
My issue is once I get the data I want to be able to write this to an existing JSON file. my api is 18 so can't use FILEwriter i am trying to make the app available to pretty much everyone. A point in the right direction would be great.
If you want to write to a file packaged in the raw folder, you will have to copy it to the local file system first. Resources contained in your raw directory in your project will be packaged inside your APK and will not be writeable at runtime. Consider looking at the Internal or External Data Storage APIs.
Update raw resources is not possible

How to write in json file with Android

Hello ! I want to change the values ​​in my json file called "etatButton.json" but I do not know how.
[
{
"bouton1":"on",
"bouton2":"on",
"bouton3":"on",
"bouton4":"off",
"bouton5":"on",
"bouton6":"on",
"bouton7":"on",
"bouton8":"on",
"bouton9":"off",
"bouton10":"off"
}
]
For example I want to change the value of "bouton1" from "on" to "off" after onClick event like this one :
public void writeJson(View view) {
// Write smth in json file
}
Thank you !
This code can get you started....
try {
JSONArray json = new JSONArray();
JSONObject jsonobject = new JSONObject();
jsonobject.put("k1", "v1");
jsonobject.put("k2", "v2");
json.put(jsonobject);
System.out.println(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OUTPUT:
[{"k1":"v1","k2":"v2"}]
If you want to be able to change v1 or v2, just use variables

For loop printing String only once when the condition is equal to 25

I'm trying to print out an object in the JSON using Facebook Graph API.
Here's my code:
try{
JSONArray data = innerJson.getJSONArray("data");
Log.d("innerDataLength", String.valueOf(data.length()));
for (int i = 0; i<data.length(); i++) {
String message = data.getJSONObject(i).getString("message");
Log.d("message", message);
}
} catch (JSONException e) {
Log.d("exception", e.getMessage());
}
Here's output:
D/innerDataLength: 25
D/message: "blah blah blah"
D/exception: No value for message
As you can see the condition i.e. data.length() is 25 then why am I getting the message printed out only once?
Note that you get an exception:
D/exception: No value for message
It indicates that the second object in JSONArray has no message property. Looks like it's optional, so you need to check whether message property exists first.
Update:
try{
JSONArray data = innerJson.getJSONArray("data");
Log.d("innerDataLength", String.valueOf(data.length()));
for (int i = 0; i < data.length(); i++) {
JSONObject obj = data.getJSONObject(i);
if (obj.has("message")) {
String message = obj.getString("message");
Log.d("message", message);
}
if (obj.has("story")) {
String story= obj.getString("story");
Log.d("story", story);
}
}
} catch (JSONException e) {
Log.d("exception", e.getMessage());
}
some of object in innerJson.getJSONArray("data") array don't has message
to check what i say comment the line inside loop and just print i will get 0 to 24
to avoid that surrounded the statment of parsing message with try and catch to avoid parsing object that not contain message
you can also print data.getJSONObject(i).toString to see parsing object

Facing issue in Json parsing user profile feed

I am working on a project in which I have to parse user feed data
using Json.
Here is the url of json:
http://ourfield.affixwebsolution.com/api/feed?data={%22userId%22:210}
This is my code where I am parsing the json
public static ArrayList<FeedDataClass> parseFeedddata(String res)
{
ArrayList<FeedDataClass>arr =new ArrayList<FeedDataClass>();
FeedDataClass obj=new FeedDataClass();
JSONArray jsonArray ;
JSONObject jsonInnerObj = null;
try {
JSONObject jsonObject =new JSONObject(res);
jsonArray =jsonObject.getJSONArray("data");
Log.d("eaweaer", jsonArray.toString());
for (int i = 0; i < jsonArray.length(); i++) {
jsonInnerObj=jsonArray.getJSONObject(i);
try {
obj.strid = jsonInnerObj.getString("id");
} catch (Exception e) {
// TODO: handle exception
}
try {
JSONObject timeline = new JSONObject(jsonInnerObj.getJSONObject("timeline").toString());
obj.strusername=timeline.getString("username");
Log.d("efe", obj.strusername);
obj.strurl=timeline.getString("avatar_url");
Log.d("aeefwe", obj.strurl);
} catch (Exception e) {
// TODO: handle exception
}
try {
obj.strtext=jsonInnerObj.getString("text");
Log.d("qeeqf", obj.strtext);
} catch (Exception e) {
// TODO: handle exception
}
arr.add(obj);
}
} catch (Exception e) {
// TODO: handle exception
}
return arr;
}
now the problem is, there are total three posts in json, but everytime
I am getting last feed . also it is getting printed 3 times in UI
because loop is running perfectly. dont know what is the mistake I am
doing here.
Help me to sort out this issue, Thank in advance.
You have only one instance of obj which keeps on updating the same memory location. In the final loop cycle it gets updated with 3rd value and shows you. But yes you add it 3 times in the list so you have same object thrice.
Move
FeedDataClass obj=new FeedDataClass();
JSONObject jsonInnerObj = null;
inside for loop.

Type mismatch: cannot convert from Object to JSONObject

I'm relatively new to Android development and am writing my first REST-based app. I've opted to use the Android Asynchronous HTTP Client to make things a bit easier. I'm currently just running through the main "Recommended Usage" section on that link, essentially just creating a basic static HTTP client. I'm following the code given, but changing it around to refer to a different API. Here's the code in question:
public void getFactualResults() throws JSONException {
FactualRestClient.get("q=Coffee,Los Angeles", null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONArray venues) {
// Pull out the first restaurant from the returned search results
JSONObject firstVenue = venues.get(0);
String venueName = firstVenue.getString("name");
// Do something with the response
System.out.println(venueName);
}
});
}
The String venueName = firstVenue.getString("name"); line is currently throwing an error in Eclipse: "Type mismatch: cannot convert from Object to JSONObject". Why is this error occurring? I searched other threads which led me to try using getJSONObject(0) instead of get(0) but that led to further errors and Eclipse suggesting using try/catch. I haven't changed any of the code on the tutorial, save for the variable names and URL. Any thoughts/tips/advice?
Thanks so much.
EDIT:
Here is the onSuccess method, modified to include the try/catch blocks suggested. Eclipse now shows the "local variable may not have been initialized" for firstVenue here: venueName = firstVenue.getString("name"); and for venueName here: System.out.println(venueName); Even if I initialize String venueName; directly after JSONObject firstVenue; I still get the same error. Any help in resolving these would be greatly appreciated!
public void onSuccess(JSONArray venues) {
// Pull out the first restaurant from the returned search results
JSONObject firstVenue;
try {
firstVenue = venues.getJSONObject(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String venueName;
try {
venueName = firstVenue.getString("name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Do something with the response
System.out.println(venueName);
}
You can try to convert object you are getting from querying to String and then use
final JSONObject jsonObject = new JSONObject(stringresult);
I was getting same error earlier, it worked for me.
Yes, you should be using getJSONObject to ensure that the value you obtain is a JSON object. And yes, you should catch the possible JSONException which is thrown if that index in the array doesn't exist, or does not contain an object.
It'll look something like this:
JSONObject firstVenue;
try {
firstVenue = venues.get(0);
} catch (JSONException e) {
// error handling
}
convert obj to json Object:
Object obj = JSONValue.parse(inputParam);
JSONObject jsonObject = (JSONObject) obj;
The solution provided by Shail Adi only worked for me by setting the initial values of firstVenue and venueName to null. Here's my code:
JSONObject firstVenue = null;
try {
firstVenue = (JSONObject)venues.get(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String venueName = null;
try {
venueName = firstVenue.getString("name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Do something with the response
System.out.println(venueName);

Categories

Resources