Write to JSONObject to JSONfile - java

I have an app that has to take a string, encode it into JSONObject format and write it into a JSON file in the SD. It all seems to be working fine apart from writing part. I have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />command in my MANIFEST and that's my code
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String lines[] = importantemail.split("\\r?\\n");
// String firstLine = (lines[0]);
//String secondLine = (lines[1]);
// Toast.makeText(SignificantEmailActivity.this,firstLine + secondLine,Toast.LENGTH_SHORT).show();;
JSONObject jsonObject = makeJsonObject();
try{
Writer output = null;
File file = new File(Environment.getExternalStorageDirectory()+ "importantemail.json");
if (!file.exists()) {
file.mkdirs();
}
output = new BufferedWriter(new FileWriter(file));
output.write(jsonObject.toString());
output.close();
Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
finish();
}
});
}
public JSONObject makeJsonObject()
{
JSONObject object = new JSONObject();
try {
object.put("Message ID", id);
object.put("Sender",accountStr);
object.put("Subject",subj);
object.put("E-mail:",importantemail);
}catch (JSONException e)
{
e.printStackTrace();
}
return object;
}
When I press the button I get this message from the Toast
"storage/emulated/0importantemail.json
Permission denied"
No idea why is that though

Tested, Hi replace few lines and this will fix your issue.
JSONObject jsonObject = makeJsonObject();
try{
Writer output = null;
File file = new File(Environment.getExternalStorageDirectory(), "importantemail.json");
if(file.isDirectory()){
file.delete();
}
if(!file.exists()){
file.createNewFile();
}
output = new BufferedWriter(new FileWriter(file));
output.write(jsonObject.toString());
output.close();
Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
finish();
}
public JSONObject makeJsonObject()
{
JSONObject object = new JSONObject();
try {
object.put("Message ID", 5);
object.put("Sender","test");
object.put("Subject","test");
object.put("E-mail:","test");
}catch (JSONException e)
{
e.printStackTrace();
}
return object;
}

in 6.0 or later versions of android, you must give runtime permission. check this.

Related

Read/Write and compare android external storage

public class PaymentActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
String FILENAME = "paid";
String data = "yes";
File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
try {
File myFile = new File(folder, FILENAME);
FileOutputStream fstream = new FileOutputStream(myFile);
fstream.write(data.getBytes());
fstream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
File myFile = new File(folder, FILENAME);
FileInputStream fstream = new FileInputStream(myFile);
StringBuilder sbuffer = new StringBuilder();
int i;
while ((i = fstream.read())!= -1){
sbuffer.append((char)i);
}
String haspaid = sbuffer.toString();
System.out.println("Help!"+haspaid.equals("yes"));
if (haspaid.equals("yes")) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
fstream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have a file write that inputs "yes" and a file read the reads that "yes" on external storage. I have System.out.println printed it out, and the file read/write seems to work. And yet somehow, when I compare the string resulted, it cannot be checked if it is a value.
What am I doing wrong?
use equals to check the equality of string instead of "!=" or "==".
equals checks the value, and "!=" or "==" checks the reference.

Is there problem in instagram's "graphql" api? Volley library giving error when I make request

I'm trying to get data from Instagram's graphql api.
I'm making request to "https://www.instagram.com/p/CQWYMTlqB9w/?__a=1" and volley giving me this error: Something went wrong com.android.volley.ParseError: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
It was working well until morning but when I used it before few hours then it started to give that error. for some users it is giving this error
Is graphql having any issues or problem with volley?
( if we add ?__a=1 to the end of any post link then it gives post data in the json form)
private void downloadInstaImage() {
dialog.show();
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(InstaImages.this);
if (binding.instImageaurl.getText().toString().contains("?utm_source=ig_web_copy_link")) {
String partToRemove = "?utm_source=ig_web_copy_link";
image = binding.instImageaurl.getText().toString().replace(partToRemove, "");
} else if (binding.instImageaurl.getText().toString().contains("?utm_source=ig_web_button_share_sheet")) {
String partToRemove = "?utm_source=ig_web_button_share_sheet";
image = binding.instImageaurl.getText().toString().replace(partToRemove, "");
} else {
image = binding.instImageaurl.getText().toString();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
image + "?__a=1", null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject Obj1 = null;
try {
Obj1 = response.getJSONObject("graphql");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject Obj2 = null;
try {
Obj2 = Obj1.getJSONObject("shortcode_media");
} catch (JSONException e) {
e.printStackTrace();
}
String finalImageUrl = null;
try {
finalImageUrl = Obj2.getString("display_url");
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("myapp", finalImageUrl);
Util.download(finalImageUrl, Util.RootDirectoryInstaImages, InstaImages.this, "insta" + ".png");
dialog.dismiss();
Toast.makeText(activity, "Downloading Started...", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Log.e("myapp", "Something went wrong " + error);
Toast.makeText(activity, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonObjectRequest);
}

Display a toast in Async

So I am trying to display a toast if the link that provided in "EditText" is equal to a specific link.
Else the code keep runing until result.
Thats how I tried to do(Its not detecting the link):
if (urls[0].equals ("http://api.openweathermap.org/data/2.5/weather?q=null&appid=8e19904c6a1db15924eef5084a978de7"))
{
Log.e("Test","Error!");
}
My main code,if you need anything else from the code just tell me and I will upload:
public class DownloadTask extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(final String... urls) {
Log.e("URL", "Loading url = " + urls[0]);
StringBuilder result = new StringBuilder();
if (urls[0].equals ("http://api.openweathermap.org/data/2.5/weather?q=null&appid=8e19904c6a1db15924eef5084a978de7"))
{
Log.e("Test","DSADSADASDASDAS");
}
URL url;
HttpURLConnection urlConnection = null;
try{
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line).append("\n");
}
return result.toString();
} catch (MalformedURLException e) {
result.append("Error: MalformedURLException");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
#SuppressLint("SetTextI18n")
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String weatherInfo = jsonObject.getString("weather");
Log.e("JSON data",""+weatherInfo);
Toast.makeText(MainActivity.this, mCityName +" has been loaded", Toast.LENGTH_SHORT).show();
JSONArray jArray = new JSONArray(weatherInfo);
for(int i = 0; 0 < jArray.length(); i++){
JSONObject partJson = jArray.getJSONObject(i);
mMain.setText("The Weather in " + mCityName + " is: " + partJson.getString("main"));
mDescription.setText("And " + partJson.getString("description"));
mMain.setVisibility(View.VISIBLE);
mDescription.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Thank you !
To show a Toast from a background thread you need to call it inside runOnUIThread like this:
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(this, "URL is the same", Toast.LENGTH_SHORT).show();
}
});
This is assuming your AsincTask is inside an activity class.
runOnUIThread is a method of Activity class, and you need a Context to show the Toast.
If your AsyncTask is in a separate class, you will need to provide an Activity as a parameter, or use an Intent to communicate with an Activity.

stopped unfortunately after adding the statement of notifyDataSetChaged()

I got in the data and converted them into what object I want and added them to the ArrayList which is ToDoItems(I've checked what I said above by Toast). Now I notified the adapter to fresh the screen. But error occurs. There's only one adapter and I created this method in the activity where this adapter is.
public void getImport(){
Gson gson = new Gson();
FileInputStream inStream = null;
File file = new File(getCacheDir(),"list1.txt");
try {strong text
String data = null;
inStream = new FileInputStream(file);
byte fileContent[] = new byte[(int)file.length()];
inStream.read(fileContent);
data = new String(fileContent);
if(data == null){
Toast.makeText(this, "No data to import", Toast.LENGTH_LONG).show();
}
else{
todoItems.clear();
String[] token = data.split("$$");
for(int i = 0;i<token.length;i++){
todoItems.add(i, gson.fromJson(token[i], ToDoItem.class));
}
aa.notifyDataSetChanged();
}
inStream.close();
Toast.makeText(this, "Import Successfully", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
Toast.makeText(this, "FileNotFoundException", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(this, "IOEXCEPTION", Toast.LENGTH_LONG).show();
}
}

parsing json from onClick event

In my app I have two views that parse json from my website and it works great. The last issue i have is where i am entering a number in an edit text box and attaching it to my URL to add the user to the database. That works but when that event is launched I want to parse that json. Right now it just launches the website.
My question is how do i start that intent instead of launching right to the website. I have a JSONParser and two jason activities that work great. here is my code. I am also saving the edit text field to my sd card so the user can call it again when he comes back to that view. I know how to parse the json i just do not know how to call it from the onClick event into another view.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences mysettings2 = PreferenceManager.getDefaultSharedPreferences(this);
String st1 = mysettings2.getString("THEME_PREF", "Blue");
if(st1.equals("Blue"))
{setTheme(R.style.Theme_Holo_blue); }
if(st1.equals("Red"))
{setTheme(R.style.Theme_Holo_red); }
if(st1.equals("Green"))
{setTheme(R.style.Theme_Holo_green); }
if(st1.equals("Wallpaper"))
{setTheme(R.style.Theme_Transparent); }
if(st1.equals("Holo"))
{setTheme(R.style.Theme_Holo); }
setContentView(R.layout.getscore);
getActionBar().setBackgroundDrawable(
getResources().getDrawable(R.drawable.divider));
edttext= (EditText)findViewById(R.id.editText1);
Button tutorial2 = (Button) findViewById(R.id.button1);
tutorial2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://example.com/user/"+edttext.getText() +"?token=dYG8hW5TY4LBU8jfPb10D3IcsSx8RTo6"));
startActivity(intent);
try {
File myFile = new File("/sdcard/my_IdNumber_file.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(edttext.getText());
myOutWriter.close();
fOut.close();
} catch (Exception e) {
}
}
});
btnReadSDFile = (Button) findViewById(R.id.btnReadSDFile);
btnReadSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/sdcard/my_IdNumber_file.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
edttext.setText(aBuffer);
myReader.close();
} catch (Exception e) {
}
}
this is my JSONParser activity
public class JSONParser {
static InputStream is = null;
static JSONArray jarray = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jarray;
}}
you want to parse json at the time of launching activity then parse it onCreate();

Categories