I have created a simple Layout to get information from users, and i have java programmed it to get the data and store them in an .JSON format. I took it as a string and saved them into .JSON format. But while returning return jsonObject i get an error.
Here is the code:
public class MainActivity extends AppCompatActivity {
EditText firstname, lastname, username, mail_id, mobile_no, pass;
Button submit;
JSONObject jsonObject = new JSONObject();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String FILE_NAME = "Sample.json";
firstname = (EditText) findViewById(R.id.firstname);
lastname = (EditText) findViewById(R.id.lastname);
username = (EditText) findViewById(R.id.username);
mail_id = (EditText) findViewById(R.id.mail);
mobile_no = (EditText) findViewById(R.id.phone);
pass = (EditText) findViewById(R.id.password);
submit = findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonformat();
String userString = jsonObject.toString();
File file = new File(MainActivity.this.getFilesDir(), FILE_NAME);
FileWriter fileWriter;
try {
fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(userString);
bufferedWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
File file1 = new File(MainActivity.this.getFilesDir(), FILE_NAME);
FileReader fileReader = null;
try {
fileReader = new FileReader(file1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
line = bufferedReader.readLine();
while (line != null) {
stringBuilder.append(line).append("\n");
line = bufferedReader.readLine();
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
// This responce will have Json Format String
String responce = stringBuilder.toString();
}
});
}
public JSONObject jsonformat()
{
try {
jsonObject.put("fname", firstname); // seems that it's wrong.
jsonObject.put("lname", lastname); // seems that it's wrong.
jsonObject.put("uname", username); // seems that it's wrong.
jsonObject.put("mail", mail_id); // seems that it's wrong.
jsonObject.put("Phone Number", mobile_no); // seems that it's wrong.
jsonObject.put("Password", pass); // seems that it's wrong.
//return jsonObject; // The error -- You can't return jsonObject in here. onCreate method is void method.
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
}
Build error:
/home/sim/AndroidStudioProjects/Activity/app/src/main/java/com/example/activity /MainActivity.java:55: error: incompatible types: unexpected return value
return jsonObject;
^
The .JSON file is created as per the program in the directory. But doesn't contain any value in it. just some "id" has been printed.
Dunno where did i make mistake or missed logic. Comment my mistakes.
I think your code contains some wrong logic.
first, you cannot return onCreate method. you should make seperate method to return object. I think that your code don't need return.
Second, you did put "Layout Element instance" to JSONObject.
I cannot understand why you did it.
Anyway, I changed your MainActivity code as following.
So you can made your change in new MainActivity code.
public class MainActivity extends AppCompatActivity {
EditText firstname, lastname, username, mail_id, mobile_no, pass;
Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String FILE_NAME = "Sample.json";
firstname = (EditText) findViewById(R.id.firstname);
lastname = (EditText) findViewById(R.id.lastname);
username = (EditText) findViewById(R.id.username);
mail_id = (EditText) findViewById(R.id.mail);
mobile_no = (EditText) findViewById(R.id.phone);
pass = (EditText) findViewById(R.id.password);
submit = findViewById(R.id.submit);
submit.setOnClickListener(v -> {
JSONObject jsonObject = jsonformat();
String userString = jsonObject.toString();
File file = new File(getFilesDir(), FILE_NAME);
FileWriter fileWriter;
try {
fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(userString);
bufferedWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
File file1 = new File(this.getFilesDir(), FILE_NAME);
FileReader fileReader = null;
try {
fileReader = new FileReader(file1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
line = bufferedReader.readLine();
while (line != null) {
stringBuilder.append(line).append("\n");
line = bufferedReader.readLine();
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
// This responce will have Json Format String
String responce = stringBuilder.toString();
});
}
public JSONObject jsonformat() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("fname", firstname.getText().toString());
jsonObject.put("lname", lastname.getText().toString());
jsonObject.put("uname", username.getText().toString());
jsonObject.put("mail", mail_id.getText().toString());
jsonObject.put("Phone Number", mobile_no.getText().toString());
jsonObject.put("Password", pass.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
}
Related
in my android app im trying to set 2 text views names from 2 different files but for some reason the first text view is being set as the 2nd files information "ingredient 2 " and the 2nd text view isnt being displayed at all? am i doing something wrong with the way im setting and opening my files?
public class GroceriesActivity extends AppCompatActivity {
public TextView groceryname1, groceryname2, groceryname3, groceryname4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_groceries);
groceryname1 = (TextView) findViewById(R.id.grocery1);
groceryname2 = (TextView) findViewById(R.id.grocery2);
groceryname3 = (TextView) findViewById(R.id.grocery3);
groceryname4 = (TextView) findViewById(R.id.grocery4);
String message;
String message2;
FileInputStream fis1 = null;
FileInputStream fis2 = null;
FileInputStream fis3 = null;
FileInputStream fis4 = null;
try {
fis1 = openFileInput("Ingredient1");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
InputStreamReader isr = new InputStreamReader(fis1);
BufferedReader br = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
try {
while ((message = br.readLine()) != null) {
sb.append(message);
}
} catch (IOException e1) {
e1.printStackTrace();
}
groceryname1.setText(sb.toString());
try {
fis1.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fis2 = openFileInput("Ingredient2");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
InputStreamReader isr2 = new InputStreamReader(fis2);
BufferedReader br2 = new BufferedReader(isr2);
StringBuffer sb2 = new StringBuffer();
try {
while ((message2 = br2.readLine()) != null) {
sb2.append(message2);
}
} catch (IOException e1) {
e1.printStackTrace();
}
groceryname2.setText(sb2.toString());
try {
fis2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
so as tldr im trying to set textview1 as ingredient1 and textview2 as ingredient2 but right now textview1 is being set as ingredient2 and textview2 is not being changed
EDIT: after fixing that error im now having the textview1 and textview2 being set as the first ingredient
try changing
sb.append(message2);
to
sb2.append(message2);
adminpage.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mTextView = (TextView) findViewById(R.id.dataList);
Button button = (Button) findViewById(R.id.rf);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt");
new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoList.txt");
}
});
}
public static class JSONTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
StringBuffer finalBufferedData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
String movieName = finalObject.getString("movie");
int year = finalObject.getInt("year");
finalBufferedData.append(movieName + " - " + year + "\n");
}
//JSONObject finalObject = parentArray.getJSONObject(0);
return finalBufferedData.toString();
//return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mTextView.setText(result);
}
}
So base on this what i can conclude is.
1) JSONTASK will take the url and break them in to different string and link them together and return finalBufferedData.toString();
2) The onPostExecute will take the result and set it to mTextView.
3) onclicklistener will run the function and perform step 2 and display.
Question!
I don't see anywhere in the code that call the function onPostExecute(String result) <-- what is the result?? is it the return finalBufferedData.toString()?
I am running the same function in another activity, how do i display in TextView without the onClicklistener to execute it.
1. Yes.. it is the return value(finalBufferedData.toString()).It is the output (result/return) of doInBackground method.
2. Call in onCreate or onResume for executing without onClick. eg:-
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// put the AsyncTask call here
Whenever I try to get a text document from Dropbox containing a version string, it says that it equals null even though it is supposed to equal 0.6.48. I've tried many different ways of getting the file, but its always returning null. Code:
new Thread() {
public void run() {
try {
URL textUrl = new URL(UPDATE_API); // UPDATE_API = "https://dl.dropboxusercontent.com/s/zjlxzypgqsxvtr0/version.txt?dl=1"
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
Soundboard.REMOTE_VERSION = stringText;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
What am I missing? I'm building for API 23. I have put <uses-permission android:name="android.permission.INTERNET"/> in my Android manifest.
Your code worked for me with few changes:
String UPDATE_API = "https://dl.dropboxusercontent.com/s/zjlxzypgqsxvtr0/version.txt?dl=1";
private BufferedReader bufferReader = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread() {
public void run() {
try {
URL textUrl = new URL(UPDATE_API);
bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
String StringBuffer = "";
StringBuilder stringText = new StringBuilder();
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText.append(StringBuffer);
}
Log.d("--->", stringText.toString());
Soundboard.REMOTE_VERSION = stringText;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
}
Try to close the BufferedReader in try..finally.
Use StringBuilder rather than String for concatenation
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();
I am working on an app where I need to save/read my files from Internal storage.
But it read all my data in the same TextView.
Can someone show me show,how to show the data in 2 textviews, or to show me how put the one data under the other data.
Here is my code for saving data:
private void SaveMode() {
String FILENAME ;
String Strin1= textview1.getText().toString();
String String2= textview2.getText().toString();
EditText filename1 = (EditText) findViewById(R.id.filename);
FILENAME = filename1.getText().toString();
if (FILENAME.contentEquals("")){
FILENAME = "UNTITLED";
}
String1 = textview1.getText().toString();
String2= textview2.getText().toString();
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write("Strin1.getBytes());
fos.write(String2.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
And here is my code for read my data:
private void getFilenames() {
String[] filenames = getApplicationContext().fileList();
List<String> list = new ArrayList<String>();
for(int i = 0; i<filenames.length; i++){
//Log.d("Filename", filenames[i]);
list.add(filenames[i]);
}
ArrayAdapter<String> filenameAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, list);
spinner.setAdapter(filenameAdapter);
}
public void SpinnerClick(View v) {
String selectFile = String.valueOf(spinner.getSelectedItem());
openFile(selectFile);
}
private void openFile(String selectFile) {
showData = (TextView) findViewById(R.id.show_data);
TextView showData1 = (TextView) findViewById(R.id.show_data1);
String value = "";
FileInputStream fis;
try {
fis = openFileInput(selectFile);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
showData.setText(value);
}
EDIT
I tried to edit my read code like this, but with no luck
private void openFile(String selectFile) {
TextView showData = (TextView) findViewById(R.id.show_data);
TextView showData2 = (TextView) findViewById(R.id.show_data2);
String value = "";
String[] strArray = value.split(";");
try {
FileInputStream fis = openFileInput(selectFile);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
showData.setText(value);
showData.setText(strArray[0]);
showData2.setText(strArray[1]);
}
Edit 2
Got it to work with Shobhit Puri codes
First while saving your data you might insert a delimiter in between those two string. Make sure that delimiter is not the one expected in your textViews.
While saving:
String string3 = ";";
try {
fos.write("Strin1.getBytes());
fos.write("String3.getBytes());
fos.write(String2.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
Then when you are trying to read it into value string, then split is using .split function. Eg:
String[] strArray = value.split(";");
strArray[0] will give first textview's sting and strArray[1] will give the second.
Update
private void openFile(String selectFile) {
TextView showData = (TextView) findViewById(R.id.show_data);
TextView showData2 = (TextView) findViewById(R.id.show_data2);
String value = "";
try {
FileInputStream fis = openFileInput(selectFile);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String[] strArray = value.split(";");
showData.setText(strArray[0]);
showData2.setText(strArray[1]);
}
try
{
FileInputStream fis = new FileInputStream(myInternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
myInputText.setText(myData);