How to add jsonObject to an existing JSON file in the "raw" folder Android Studio? (Java) - java

Im trying to add jsonObject to an existing JSON file in "raw" folder.
Every time the button pressed it should add to the JSON file two new variables from the plainText input. I cant figure out how to do that because I cant properly get the path of the "raw" folder.
the code that I wrote without the "adding to JSON" part
public void submit(View view) {
EditText editAmount;
EditText editReason;
Log.d("Smth", "Submit!");
editAmount = (EditText)findViewById(R.id.editAmount);
editReason = (EditText)findViewById(R.id.editReason);
String amount = editAmount.getText().toString();
String date = "18.02.2023";
String reason = editReason.getText().toString();
Log.d("Smth", amount);
Log.d("Smth", reason);
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("amount", amount);
jsonObject.put("reason", reason);
jsonObject.put("date", "18.02.2023");
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
I have tried a lot of other solutions on StackOverFlow, but all of them give me errors.
I hope you will help me with this problem of editing JSON file) Thank you

Related

How can I store list items when there is no internet connection (data come from server)

Regarding
I have a listview contains 4 items 3 of them are texts and fourth is image
all data are on server within json
the code work correctly but when the internet is off all items and list does not appear how can make the list works with and without internet connection
because I add everyday new items to database
and this my code
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("allstudents");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject respons = jsonArray.getJSONObject(i);
String id = respons.getString("id");
String name = respons.getString("name");
String info = respons.getString("info");
String img = respons.getString("img");
link = respons.getString("link");
voicelink = respons.getString("voicelink");
listitmes.add(new listitme(id, name, info, img, link, voicelink));
allitems();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
}
public void allitems() {
listAdapter lsadapter = new listAdapter(listitmes);
listView.setAdapter(lsadapter);
}
any solution please I searched a lot but no any answer
and I did not find any thing like here on StackOverflow.Com
Look at https://developer.android.com/reference/android/content/SharedPreferences.
With Shared SharedPreferences you can save the list and call it if there is no wifi!
what you can do is:
Save the data that you download, to a file (image)/properties (text) as soon as you receive data from Internet. ()
Display a message in your activity when the data was fetched (e.g. Last Synced : Timestamp).
If you can can't connect to Internet to get the new data, load the data from file/properties.
If you can't connect to Internet and don't have any saved data, display a message (e.g. can't connect to Internet - may be color it to highlight it's an error).
my 2 cents...

Display data from mysql into ListView in Android

I am currently fetching data from mysql database and displaying successfully in the TextView like this:
private void showJSON(String response){
String child_name="";
//String address="";
//String vc = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
child_name = collegeData.getString(config.KEY_NAME);
//address = collegeData.getString(config.KEY_ADDRESS);
//vc = collegeData.getString(config.KEY_VC);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Children Name:\t" + child_name);
now, rather into the TextView, I want to display it in the ListView. So How to proceed in this way as i am new to android development.
In order to populate a ListView in Android you first need to create an Adapter object where you'll define the layout of each item and the behavior of the list.
Basically what you'll have to do is:
Create an ArrayList of the objects you want to display
Create an Adapter for your list view (passing the previously created list as parameter at creation)
Set the adapter to your ListView object.
You may follow this guide for the complete details: http://www.vogella.com/tutorials/AndroidListView/article.html

How to access saved data from different method?

I am trying to save a value as a string on the device's internal memory so that it can be accessed when the app is closed and reopened by clicking another button. When I run the program, I enter values for inputs A and B, and I know it processes them through the calculations because I modified it so that it displays the answer as soon as it is calculated.
But on this version, if I click the save button, and subsequently click the Access button to show the answer and the textview labeled Previous Answer, it simply shows "xx" which is the initial value of the string I'm trying to save. So either it doesnt store the updated version which includes the answer, or the Access button is only able to access the original value of the string.
Button jSave = (Button) findViewById(R.id.iSave);
Button jAccess = (Button) findViewById(R.id.iAccess);
final String saveName="Name";
final String saveValue = "xx";
jSave.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
//Calculations. These are a part of a more complex series of
//calculations between several classes, but I've simplified it
//somewhat for this post.
EditText jInputA = (EditText)findViewById(R.id.iInputA);
double dInputA = Double.parseDouble(jInputA.getText().toString());
EditText jInputB = (EditText)findViewById(R.id.iInputB);
double dInputB = Double.parseDouble(jInputB.getText().toString());
double myAnswer = Double.parseDouble(ProfileCalculations.functionQ(jInputA, jInputB));
//Update the value of saveValue to match that of myAnswer
final String saveValue = "The answer is " myAnswer;
//Save saveValue as a string under file saveName
try{
FileOutputStream jFOS = openFileOutput(saveName, Context.MODE_PRIVATE);
jFOS.write(saveValue.getBytes());
jFOS.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Profile.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Profile.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
);
jAccess.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
try {
FileInputStream jFIS = openFileInput(saveName);
jFIS.read(saveValue.getBytes());
jFIS.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Profile.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Profile.class.getName()).log(Level.SEVERE, null, ex);
}
TextView jPreviousAns = (TextView) findViewById(R.id.iPreviousAns);
jPreviousAns.setText(saveValue + "");
}
}
);
How about shared preferences? Here's an example.
private SharedPreferences defaultPrefs;
defaultPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String url = "http://www.example.com";
SharedPreferences.Editor ed = defaultPrefs.edit();
ed.putString("homepage", url);
ed.commit();
And, later:
String url = defaultPrefs.getString("homepage", "http://www.example.com/some_default_page");
Android provides several options for you to save persistent application data. The solution you choose depends on your specific needs, such as whether the data should be private to your application or accessible to other applications (and the user) and how much space your data requires.
Your data storage options are the following:
Shared Preferences
Store private primitive data in key-value pairs.
Internal Storage
Store private data on the device memory.
External Storage
Store public data on the shared external storage.
SQLite Databases
Store structured data in a private database.
Network Connection
Store data on the web with your own network server.
For your given application of this, I would imagine that Shared Preferences or Internal Storage would be the way to go.
Internal Storage: Using this route, you would have to call openFileOutput() to start a FileOutputStream, and from there use write() to write data to the file, and close() to close the FileOutputStream.
Ex:
String FILENAME = "hello_file";
String string = "hello world!";
//Initiate
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
//Write to file
fos.write(string.getBytes());
//Close file
fos.close();
Shared Preferences: If you are to use this, then you must call edit() to get a SharedPrefrencesEditor, and then to add values to this, you would simply use putBoolean(), putString(), etc. Once you're finished you commit the data using commit().
Ex:
//Initiate Shared Preferences
SharedPreferences.Editor editor = settings.edit();
//Writes data
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
(Source)

Communicating using socketio in Android - socket.emit error

I'm trying to communicate to my nodejs application using android as client. Currently I'm using https://github.com/Gottox/socket.io-java-client repository as reference. Tried the examples of repo but no help.
NodeJS-SocketIO Code:
socket.on('new user',function(data, callback){
if (nicknames.indexOf(data)!=-1){
callback(false);
} else{
callback(true);
socket.nickname = data;
nicknames.push(socket.nickname);
updateNicknames();
}
});
Android-Java Code:
try {
JSONObject json = new JSONObject();
json.putOpt("data", "user1");
socket.emit("new user", json);
} catch (JSONException ex) {
ex.printStackTrace();
}
However, the above code results in TypeError: undefined. Please help. Thanks in advance!
You can do away with the JSON object. You could just do:
socket.emit("new user", "user1");
Not so sure about sending a JSON over, but if you wanted to, did you try:
JSONArray array = new JSONArray();
array.put("data", "user1");
socket.emit("new user", array);
Pretty sure JSONs need to have the enclosing brackets.

Java / Android: Get Facebook User Info From Graph Api, Display in TextView

I'm trying to learn Java right now and I've jumped in the deep end by starting with the Android Faceobok API. Right now, I'm trying to get some information from my graph data (a friend in this case) and display it in a text view. This seems rather trivial but it has been anything but.
JSONObject json_data = null;
try
{
JSONObject response = Util.parseJson(facebook.request("/me/friends", mBundle, "GET")); // Get a friend information from facebook
JSONArray jArray = response.getJSONArray("data");
json_data = jArray.getJSONObject(0);
String name = json_data.getString("name");
mText.setText(name);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (FacebookError e)
{
e.printStackTrace();
}
The TextView doesn't change when I do this and I'm not exactly sure where I've gone wrong.
As an aside, there is a shortage of good Android Facebook API tutorials out there. Most are hundreds of lines of code; I don't have the energy or patience to consume all of that.
I have a feeling your initial request isnt working properly. you should try this line instead:
JSONObject response = Util.parseJson(facebook.request("me/friends"));
Firstly I think in your initial request, it should be "me/friends" rather than "/me/friends". Secondly you dont necessarily need the mBundleor "GET" parameters in what you're trying to achieve. Have you even defined parameters in mBundle? You're also getting information from the request method, so the "GET" parameter isn't necessary.
Try the line i just wrote, as it is simpler and will get your friends information. The rest of your code is fine.
Your assertion about being "trivial" is essentially true, but generally speaking "jumping into the deep end" rarely results in anything other than a drowning.
I'm going to be "that guy" and recommend you actually get to the point of having a general understanding and minimal competency in Java before tackling someone else's API. Once you know how Java works - the "PME" ... properties, methods, and events - learning anyone's API becomes just a question of following the proper steps.
Besides that little bit of PS, answer the following:
1) received data from your source?
2) what thread are you invoking this on?
3) any of the objects null?
4) any exceptions being thrown when you look in the Console or Log (print those out to the Log versus your current implementation)?
And, not for nothing, but if you don't have the time or patience to learn the "how's and why's" of an API or software dev in general then this will be a long exercise for you if the work ever becomes non-trivial.
Just one man's opinion who also has attempted to drink from fire hose before.
Update: Here's all of my code:
public class FriendsActivity extends Activity {
/** Called when the activity is first created. */
Facebook facebook = new Facebook("194653157245506");
TextView mText;
Bundle mBundle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mText = (TextView) this.findViewById(R.id.text);
facebook.authorize(this, new String[] {"offline_access", "user_interests", "friends_interests"},
new DialogListener() {
#Override
public void onComplete(Bundle values) {}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
JSONObject json_data = null;
try
{
JSONObject response = Util.parseJson(facebook.request("/me/friends", mBundle, "GET")); // Get a friend information from facebook
JSONArray jArray = response.getJSONArray("data");
json_data = jArray.getJSONObject(0);
String name = json_data.getString("name");
Log.i("friend is", name);
mText.setText(name);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (FacebookError e)
{
e.printStackTrace();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
}
I may be a little off key. but I have done facebook api development in C#, and i am wondering if you have had the client login.
Facebook works with OAuth to allow you to authorize through them for a client. (Even your own account as the client) therefore you may need to login.
Another thing to look at is, do you have the TextView that is in the Activity that is being displayed..
Try putting in a breakpoint and looking over the code as it is executing, Debug View is great for that.
see if your response is being populated.
make sure you have the Text from the Activity.
mText = (TextView)findViewById(R.id.TextView1); //or whatever you named it.
Also the LogCat should show you the stack trace for any errors that occur, maybe posting some of the output would help

Categories

Resources