I am trying to send data to url from where i am parsing json data and i want to know can we edit json data in url if we created random json store from myjson.com or we have to maintain our own server to edit json data.Here i created random json store and i am parsing data from that url and i also wanted to edit the data in url thats the problem i was not able to do .Its not working.please help???
This was structure
[{"name":"pavan","hit":true}]
this was mainactivity code from where fetchdata executes in background
public class MainActivity extends AppCompatActivity {
Button click;
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click=(Button)findViewById(R.id.button);
data=(TextView)findViewById(R.id.fetcheddata);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fetchdata process=new fetchdata();
process.execute();
}
});
}
}
This is fetchdata class from where fetching data from url and displaying in text view of mainactivity
public class fetchdata extends AsyncTask<Void,Void,Void> {
String data="";
String dataparsed="";
String singleparsed="";
boolean flag=false;
#Override
protected Void doInBackground(Void... params) {
try {
URL url=new URL("https://api.myjson.com/bins/1854yb");
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
InputStream inputStream=httpURLConnection.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
String line="";
while (line!=null)
{
line=bufferedReader.readLine();
data=data+line;
}
JSONArray JA=new JSONArray(data);
for(int i=0;i<JA.length();i++)
{
JSONObject JO= (JSONObject) JA.get(i);
singleparsed="Name:"+JO.get("name")+"\n"+"Feed key:"+JO.get("hit");
dataparsed=dataparsed+singleparsed;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
MainActivity.data.setText(this.dataparsed);
JSONObject postData = new JSONObject();
try {
postData.put("name","sai");
postData.put("hit", false);
new senddata().execute("https://api.myjson.com/bins/1854yb", postData.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is senddata to url code from postexecute of fetchdata this was executing and nothing is happening in url please help i am working on this from 3 days
public class senddata extends AsyncTask<String,Void, String> {
String data="";
String dataparsed="";
String singleparsed="";
boolean flag=false;
#Override
protected String doInBackground(String... params) {
String data = "";
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes("PostData=" + params[1]);
wr.flush();
wr.close();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
data += current;
}
dataparsed=data;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e("TAG", result);
}
}
This api doesn't accept any paramter after its url.
It is a get method Api url not post method . Try running it in post method in postman , it will give error.
If u run in get method ,it will produce same output ,even if u add something after url :-"https://api.myjson.com/bins/1854yb"
I think you have some issue with myJson in creating api. If you are a beginner in android your can also try with Link for ready made Api for Android
They have created different kind of Apis for understanding the json concept.
also get some update about PostMan Link for postman
Related
Here I'm trying to read an HTML file and log it but the problem is every time i check the logs I see hundreds of numbers instead of the actual code of the HTML.
I added the Internet permission in case you asked
public class MainActivity extends AppCompatActivity {
public class downloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += data;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return "Failed";
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("Result is:", s);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downloadTask task = new downloadTask();
task.execute("https://samples.openweathermap.org/data/2.5/weather?id=2172797&appid=439d4b804bc8187953eb36d2a8c26a02");
}
}
the response of API is in JSON format.
You must parse JSON response before getting data.
Here an example of JSON parsing in java.
Good luck!
In my MainActivity.java i have set some text to a TextView, how do I get the text that I had set to the TextView
My Textview -
<TextView
android:id="#+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible" />
ASyncTask -
public class fetchdata extends AsyncTask<Void, Void, Void> {
private String data = "";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://blablabla.com/hello.json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
data = bufferedReader.readLine();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.show.setText(this.data);
}
}
MainActivity -
private static TextView show;
...... show is static
show = findViewById(R.id.show);
String data = show.getText().toString();
but data is empty instead of me getting "this is the text I want to get"
Considering the fact that the following two lines are together,
show = findViewById(R.id.show);
String data = show.getText().toString();
I'm gonna guess that they are in the onCreate, thereby resulting in empty data.
You'll need to wait for the AsyncTask to complete and TextView to have it's value set in onPostExecute before you try to get it in the UI thread. (You could use a callback)
class fetchdata extends AsyncTask<Void, Void, String> {
private String data = "";
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL("https://blablabla.com/hello.json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
return data = bufferedReader.readLine();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
show.setText(aVoid);
}
}
I want to write a android code to retrieve json array but I cannot do it. I have tried many tutorials but nothing seemed to worked. Please anyone solve this problem.
Here is the Json:
{
"total_records":"3370",
"count":100,
"records": [
{"id":"175274241",
"timestamp":"1494685823",
"state":"Telangana",
"district":"Warangal",
"market":"Mahabubabad",
"commodity":"Cotton",
"variety":"Desi",
"arrival_date":"13/05/2017",
"min_price":"4150",
"max_price":"4150",
"modal_price":"4150" }
]
}
Here is the Android code
public class MainActivity extends Activity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncLogin().execute();
}
private class AsyncLogin extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL("website url");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
pdLoading.dismiss();
try {
List<String> categories = new ArrayList<String>();
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String str = json_data.getString("records");
Toast.makeText(MainActivity.this,str,Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(MainActivity.this,""+e,Toast.LENGTH_LONG).show();
}
}
}
}
Anyone write a android code for above json data.
If your json data is in string jsonStr.By the help of following code ,you can parse your json
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String records = jsonObj.getString("total_records");
String count= jsonObj.getString("count");
// Getting JSON Array node
JSONArray records= jsonObj.getJSONArray("records");
// looping through All Contacts
for (int i = 0; i < records.length(); i++) {
JSONObject c = records.getJSONObject(i);
String id = c.getString("id");
String timestamp= c.getString("timestamp");
String state= c.getString("state");
String district= c.getString("district");
String market= c.getString("market");
String commodity= c.getString("commodity");
String variety= c.getString("variety");
String arrival_date= c.getString("arrival_date");
String min_price= c.getString("min_price");
String max_price= c.getString("max_price");
String modal_price= c.getString("modal_price");
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
I have designed an application with a successful login and register system in Android Studio. I am hosting my DB on hosting24.
I need to pull data from the DB and display it onscreen inside the application.
Can anyone suggest how to? I have a heap of code written for this application so any suggestions of what code is needed to see I will post. I am not too sure what code I would need to post here..
Scenario would be if a teacher logs into the application they will see a list of registered students and corresponding data related to those students.
<?php
$con = mysqli_connect("host", "username", "pw", "db");
$FirstName = $_POST["FirstName"];
$LastName = $_POST["LastName"];
$statement = mysqli_prepare($con, "SELECT * FROM Student");
mysqli_stmt_bind_param($statement, "ss",$FirstName, $LastName);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["FirstName"] = $FirstName;
$response["LastName"] = $LastName;
}
echo json_encode($response);
?>
Here is my java code
public class UserAreaActivity extends AppCompatActivity implements View.OnClickListener{
Button fetch;
TextView text;
EditText et;
HttpURLConnection urlConnection = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
fetch= (Button) findViewById(R.id.fetch); //XML Button to get the data
fetch.setOnClickListener(this);
}
class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new ProgressDialog(UserAreaActivity.this);
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Fetching data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
task.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
try {
URL url = new URL("MY PHP URL");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
is = urlConnection.getInputStream();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
// ambil data dari Json database
try {
JSONArray Jarray = new JSONArray(result);
for(int i=0;i<Jarray.length();i++)
{
JSONObject Jasonobject = null;
Jasonobject = Jarray.getJSONObject(i);
//get an output on the screen
String firstName = Jasonobject.getString("FirstName");
String db_detail="";
if(et.getText().toString().equalsIgnoreCase(firstName)) {
db_detail = Jasonobject.getString("detail");
text.setText(db_detail);
break;
}
}
this.progressDialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
Result in this is it hangs on fetching data for me. I just need a list of names to print to screen
First you will need to create a server side file which can fetch the data from database and post it as JSON (or other format if you prefer)
<?php
// Code to connect to database
// fetch and process the data
// print json echo json_encode($output)
?>
Suppose the above php file is at http://example.com/process.php
In Android you need to make an asynchronous HTTP request to the JSON API you created earlier (at http://example.com/process.php). One way is to use an AsyncHttpClient to fetch data
public void loadFromWeb(){
RequestParams params = new RequestParams();
AsyncHttpClient client = new AsyncHttpClient();
params.put("parameter", data);
client.post("http://example.com/process.php", params, new JsonHttpResponseHandler() {
#Override
public void onStart() {
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
//process the response
//Do what you want with data, display in your layout
} catch (Exception e) {
//catch exception
}
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
// Process failure
}
});
}
You might want to read more about AsyncHttpClient for this.
Or you can have a look at other ways to make asynchronous calls, one such library is RetroFit
public class MainActivity extends AppCompatActivity {
Where I set up the url and HttpUrlConnection which allows the program to read the contents of the url.
public class DownloadTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try{
url = new URL(urls[0]);
urlConnection =(HttpURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data != -1){
char current = (char) data;
result += current;
data =reader.read();
}
return result;
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
String result = null;
try {
result = task.execute("http://www.historyplace.com/specials/").get();
Log.i("Contents of URL", result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
I believe my code is written correctly because the logCat does display a few lines of code. Unfortunately it does not display all of it. I am trying to first retrieve all of the code so I can use Regex to extract certain pictures and names for an educational school project.