parsing json from onClick event - java

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();

Related

Android : Cannot return the values

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;
}
}

Java: Can't convert string to array

I can't convert a string to an array!
String text = "";
String[] textsplit = {};
//Stuff
The app set the content of an online txt file in a string:
The online txt file contain: hello,my,name,is,simone
[...] //Downloading code
text = bo.toString(); //Set the content of the online file to the string
Now the string text is like this:
text = "hello,my,name,is,simone"
Now i have to convert the string to an array that must be like this:
textsplit = {"hello","my","name","is","simone"}
so the code that i use is:
textsplit = text.split(",");
But when i try to use the array the app crash! :(
For example:
textview.setText(textsplit[0]); //The text of the textview is empity
textview.setText(textsplit[1]); //The app crash
textview.setText(textsplit[2]); //The app crash
etc...
where am I wrong? thanks!
EDIT: This is the code:
new Thread() {
#Override
public void run() {
String path ="http://www.luconisimone.altervista.org/ciao.txt";
URL u = null;
try {
u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream in = c.getInputStream();
final ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
in.read(buffer); // Read from Buffer.
bo.write(buffer); // Write Into Buffer.
runOnUiThread(new Runnable() {
#Override
public void run() {
text = bo.toString();
testo.setText("(" + text + ")");
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
// Here all variables became empity
textsplit = text.split(",");
datisplittati.setText(textsplit[0]);
Try :
String text = "hello,my,name,is,simone";
String[] textArr = text.split(Pattern.quote(","));
You can get string using AsyncTask
private class GetStringFromUrl extends AsyncTask<String, Void, String> {
ProgressDialog dialog ;
#Override
protected void onPreExecute() {
super.onPreExecute();
// show progress dialog when downloading
dialog = ProgressDialog.show(MainActivity.this, null, "Downloading...");
}
#Override
protected String doInBackground(String... params) {
// #BadSkillz codes with same changes
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(entity);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line + "\n");
}
String result = total.toString();
Log.i("Get URL", "Downloaded string: " + result);
return result;
} catch (Exception e) {
Log.e("Get Url", "Error in downloading: " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// TODO change text view id for yourself
TextView textView = (TextView) findViewById(R.id.textView1);
// show result in textView
if (result == null) {
textView.setText("Error in downloading. Please try again.");
} else {
textView.setText(result);
}
// close progresses dialog
dialog.dismiss();
}
}
and use blow line every time that you want:
new GetStringFromUrl().execute("http://www.luconisimone.altervista.org/ciao.txt");
You're using new thread to get data from an url. So in runtime, data will be asynchronous.
So when you access text variable (split it), it's still not get full value (example reason: network delay).
Try to move the function split after text = bo.toString(); , I think it will work well.

Displaying database records in android using JAVA RESTful webservice

I am trying to display database record using java restful web service. I have able to create a login form using it but I cannot display the records on the database. I tried this code but its not working at all. When button is pressed nothing happens. Heres my code.
DriverDetails.java
class Details extends Activity {
TextView name1;
TextView plate1;
Button Btngetdata;
//URL to get JSON Array
private static String url = "http://192.168.254.108:8080/taxisafe/display/taxidetails";
//JSON Node Names
private static final String TAG_USER = "taxi";
private static final String TAG_NAME = "taxi_name";
private static final String TAG_EMAIL = "taxi_plate_no";
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
name1 = (TextView)findViewById(R.id.name);
plate1 = (TextView)findViewById(R.id.plate);
}
#Override
protected JSONObject doInBackground(String... args) {
HttpConnection jParser = new HttpConnection();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
//Set JSON Data in TextView
name1.setText(name);
plate1.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
HttpConnection.java
public class HttpConnection {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public HttpConnection() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I suggest adding Volley to your project
https://developer.android.com/training/volley/index.html
and following the example here https://developer.android.com/training/volley/request.html#request-json
You will not need to create your own HTTP request. Let Volley handle the network request using JSONObjectRequest

Error when parsing json result from http post on android app

I have a php script that returns this json array.
{"PID":"1","PName":"Guitar","Brand":"Fender","Price":"110","Cat#":"1","Typ#":"1"}
I am making a simple app that places these results into several text views. only one product is returned each time as above.
when I run the app I get this Error: org.json.JSONException: Value
{"Typ#":"1","Brand":"test","Cat#":"1","PName":"Test","PID":"2","Price":"120"}
of type org.json.JSONObject cannot be converted to JSONArray.
Here is my code. Is there something wrong with the json result or the code?
public class MainActivity extends ActionBarActivity {
TextView tvname;
TextView tvbrand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvname = (TextView) findViewById(R.id.tvName);
tvbrand = (TextView) findViewById(R.id.tvBrand);
Button btnPost = (Button) findViewById(R.id.btnPost);
btnPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new getPro().execute();
}
});
}//end of on create
private class getPro extends AsyncTask<String,String,Void>{
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
getPro.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... strings) {
String url_select = "http://10.0.2.2/OnetoOne/getProduct.php";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("pid", "2"));
try {
// Set up HTTP post
// HttpClient is more then less deprecated. Need to change to URLConnection
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// Read content & Log
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
//parse JSON data
try {
JSONArray jArray = new JSONArray(result);
//JSONObject jObject = jArray.getJSONObject(0);
String anem = jArray.getJSONObject(0).getString("PName");
//String getname = jObject.getString("PName");
//String getbrand = jObject.getString("Brand");
tvname.setText(anem);
//tvbrand.setText(getbrand);
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
}
}
}//end of async
}//end of class
Any help would be greatly appreciated.
That's not an array it's an object
JSONObject jObject = new JSONObject(result);
String anem = jObject.getString("PName");
tvname.setText(anem);
{"Typ#":"1","Brand":"test","Cat#":"1","PName":"Test","PID":"2","Price":"120"} of type org.json.JSONObject cannot be converted to JSONArray.
You are trying to convert a JSONObject into a JSONArray, this is your error.
Use :
JSONOjbect jso = new JSONObject(result);
A JSONObject Start with { and end with }.
A JSONArray Start with [ and end with ].

how to consume json web service deployed in iis in android

i have created restfull webservices (retun json data) in asp.net and deploye it on iis.now i want to consume that webServices in android..but in android its work fine in emulator but on android device its give error...
Error: Connection to" //http://ipAddress.:6547/" refused
plz help
thats code
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.recent_jsonws_map_layout);
}
public String readJSONFeed(String URL)
{
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try
{
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200)
{
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line);
}
inputStream.close();
}
else
{
Log.d("JSON", "Failed to download file");
}
}
catch (Exception e)
{
Log.e("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
#SuppressWarnings("unused")
private class ReadWeatherJSONFeedTask extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... urls)
{
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result)
{
try
{
jsonObject = new JSONObject(result);
jsonArrayGeoPoint = new JSONArray(jsonObject.getString("jsondataResult").toString());
Toast.makeText(getApplicationContext(), jsonArrayGeoPoint.getString(0).toString()+"||"+jsonArrayGeoPoint.getString(1).toString(), Toast.LENGTH_SHORT).show();
String[] strArrtemp=new String[5];
Double[] strArrLat = new Double[5];
Double[] strArrLon = new Double[5];
for(int i=0; i<jsonArrayGeoPoint.length(); i++)
{
try
{
strArrtemp[i]=jsonArrayGeoPoint.getString(i).toString();
}
catch (JSONException e)
{
Log.e("JsonArray ERROR",e.getLocalizedMessage());
}
}
String[] arrytemp = new String[2];
String temp;
for(int i=0; i<strArrtemp.length; i++)
{
temp = strArrtemp[i].toString();
strArrLat[i]=Double.parseDouble(temp.substring(0,6));
strArrLon[i]=Double.parseDouble(temp.substring(7,13));
}
Toast.makeText(getApplicationContext(), "Lat1="+strArrLat[1].toString()+" & Lon1="+strArrLon.toString(), Toast.LENGTH_SHORT).show();
Button getDir;
getDir = (Button)findViewById(R.id.getLocationBtn);
getDir.setText(strArrLat[1].toString());
}
catch (Exception e)
{
Log.e("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
}
}
enter code here
public void btnGetWeather(View view)
{ newReadWeatherJSONFeedTask().execute(http://ipAddress.:6547/RestServiceImpl.svc/jsondata/");
}
}
instead of using localhost use 10.0.2.2:portnumber

Categories