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
Related
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
So I have been trying to workout an authentication system for my app. I have a REST API running, which is tested to work with Oauth2 authentication using CURL from my laptop, so that I can get tokens for the API.
My result variable within the doInBackground does get a JSON response from my API, giving the access token information, its life, etc.
Like I get this value in result when I debug:
{"access_token":"4Oq6o8oAGRf4oflu3hrbsy18qeIfG1","expires_in":36000,"token_type":"Bearer","scope":"read write","refresh_token":"iocSNJ2PTVbph2RnWmcf0Zv69PDKjw"}
However, my onPostExecute for some reason is not getting called.
Here is my code.
login.java
public class Login extends AppCompatActivity {
Button LoginButton, RegButton;
EditText uUserName, uPassWord;
WSAdapter.SendAPIRequests AuthHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//SetupHomeBtn = (ImageButton) findViewById(R.id.SetupHomeBtn);
LoginButton = (Button) findViewById(R.id.LoginButton);
RegButton = (Button) findViewById(R.id.LoginRegister);
uUserName = (EditText) findViewById(R.id.LoginUserBox);
uPassWord = (EditText) findViewById(R.id.LoginPassBox);
//AuthHelper = new WSAdapter().new SendDeviceDetails();
// Moves user to the main page after validation
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// gets the username and password from the EditText
String strUserName = uUserName.getText().toString();
String strPassWord = uPassWord.getText().toString();
// API url duh
String APIUrl = "http://192.168.0.18:8000/auth/token/";
// If the user is authenticated, then transfer to the MainActivity page
if (APIAuthentication(strUserName, strPassWord, APIUrl)){
startActivity(new Intent(Login.this, Posts.class));
}
}
});
RegButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// gets the username and password from the EditText
startActivity(new Intent(Login.this, Register.class));
}
});
}
private boolean APIAuthentication(String un, String pw, String url){
// when it wasn't static -> AuthHelper = new WSAdapter().new SendAPIRequests();
AuthHelper = new WSAdapter.SendAPIRequests();
try {
// Putting the data to be posted in the Django API
AuthHelper.execute(un, pw, url);
return true;
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
WSAdapter.java
public class WSAdapter {
static public class SendAPIRequests extends AsyncTask<String, String, String> {
// Add a pre-execute thing
#Override
protected String doInBackground(String... params) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Log.e("TAG", params[0]);
Log.e("TAG", params[1]);
//String data = "";
StringBuilder result = new StringBuilder();
HttpURLConnection httpURLConnection = null;
try {
// Sets up connection to the URL (params[0] from .execute in "login")
httpURLConnection = (HttpURLConnection) new URL(params[2]).openConnection();
// Sets the request method for the URL
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
httpURLConnection.setRequestProperty("Accept","application/json");
// Tells the URL that I am sending a POST request body
httpURLConnection.setDoOutput(true);
// Tells the URL that I want to read the response data
httpURLConnection.setDoInput(true);
// JSON object for the REST API
JSONObject jsonParam = new JSONObject();
jsonParam.put("client_id", "mYIHBd321Et3sgn7DqB8urnyrMDwzDeIJxd8eCCE");
jsonParam.put("client_secret", "qkFYdlvikU4kfhSMBoLNsGleS2HNVHcPqaspCDR0Wdrdex5dHyiFHPXctedNjugnoTq8Ayx7D3v1C1pHeqyPh1BjRlBTQiJYSuH6pi9EVeuyjovxacauGVeGdsBOkHI3");
jsonParam.put("username", params[0]);
jsonParam.put("password", params[1]);
jsonParam.put("grant_type", "password");
Log.i("JSON", jsonParam.toString());
// To write primitive Java data types to an output stream in a portable way
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
// Writes out a byte to the underlying output stream of the data posted from .execute function
wr.writeBytes(jsonParam.toString());
// Flushes the jsonParam to the output stream
wr.flush();
wr.close();
// // Representing the input stream
InputStream in = new BufferedInputStream(httpURLConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
// reading the input stream / response from the url
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Disconnects socket after using
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
Log.e("TAG", result.toString());
return result.toString();
}
#Override
protected void onPostExecute(String result) {
//super.onPostExecute(result);
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
}
}
SO I actually just figured this out. It turns out that my code is running fine, its just that when I debug, I didn't realize theres a button to the side "Run the new thread" or something like that. It then sent me to the onPostExecute. Sorry for being a noob. Hopefully this can be a help to somebody in the future with this simple mistake.
So I have been trying to make a feature in my app where I can login and then fetch data from my database through the Django REST Framework. My logging in works as it only uses POST, but retrieving items does not work.
For some reason my AsyncTask does not get called for retrieving posts.
I have placed my AsyncTask for both activities, which are login and posts, on a separate java file only for handling Web Server stuff.
I am wondering if this is because I should put AsyncTask on each activities.
login.java
public class Login extends AppCompatActivity {
Button LoginButton;
EditText uUserName, uPassWord;
WSAdapter.SendAPIRequests AuthHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//SetupHomeBtn = (ImageButton) findViewById(R.id.SetupHomeBtn);
LoginButton = (Button) findViewById(R.id.LoginButton);
uUserName = (EditText) findViewById(R.id.LoginUserBox);
uPassWord = (EditText) findViewById(R.id.LoginPassBox);
//AuthHelper = new WSAdapter().new SendDeviceDetails();
// Moves user to the main page after validation
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// gets the username and password from the EditText
String strUserName = uUserName.getText().toString();
String strPassWord = uPassWord.getText().toString();
// API url duh
String APIUrl = "http://192.168.0.18:8000/token-auth/";
// If the user is authenticated, then transfer to the MainActivity page
if (APIAuthentication(strUserName, strPassWord, APIUrl)){
startActivity(new Intent(Login.this, Posts.class));
}
}
});
}
private boolean APIAuthentication(String un, String pw, String url){
// when it wasn't static -> AuthHelper = new WSAdapter().new SendAPIRequests();
AuthHelper = new WSAdapter.SendAPIRequests();
JSONObject postData = new JSONObject();
try {
// Attempt to input info to the Django API
postData.put("username", un);
postData.put("password", pw);
// Putting the data to be posted in the Django API
AuthHelper.execute(url, postData.toString());
return true;
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
posts.java
public class Posts extends AppCompatActivity {
TextView postsSect;
Button postsDoneBtn;
WSAdapter.SendAPIRequests PostsHelper;
StringBuilder postsBuffer = new StringBuilder();
#Override
protected void onResume(){
super.onResume();
PostsDetails postDetailsHelper = new PostsDetails();
postDetailsHelper.ListPosts();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
PostsDetails postDetailsHelper = new PostsDetails();
postsDoneBtn = (Button) findViewById(R.id.PostsDoneButton);
postDetailsHelper.callPostDetails("192.168.0.18:8000/api");
postDetailsHelper.ListPosts();
postDetailsHelper.postDetailsCalled('n');
postsDoneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Posts.this, MainActivity.class));
}
});
}
public class PostsDetails {
//String post_title, post_content;
ArrayList<Integer> post_id = new ArrayList<Integer>();
ArrayList<String> post_title = new ArrayList<String>();
ArrayList<String> post_content = new ArrayList<String>();
boolean isPDCalled;
// sets if Post details are called
boolean postDetailsCalled(char called) {
if (called == 'y'){
return true;
}
return false;
}
// checks if postsDetails functions are called for AsyncTask
boolean getIsPDCalled(){
return isPDCalled;
}
// calls the execute for AsyncTask
private void callPostDetails(String theurl){
PostsHelper = new WSAdapter.SendAPIRequests();
// sets if post details are called
postDetailsCalled('y');
// executes AsyncTask
PostsHelper.execute(theurl);
}
// sets values for the posts arrays
public void setPost(int p_id, String p_title, String p_content) {
post_id.add(p_id);
post_title.add(p_title);
post_content.add(p_content);
}
// Lists the posts from the database
public void ListPosts() {
/////////// add functionality if a post was deleted and was clicked
postsSect = (TextView) findViewById(R.id.PostsSection);
postsSect.setText(post_title.get(post_title.size()) + "\n");
for (int i = post_id.size() - 1; i > 0; i--)
{
postsSect.append(post_title.get(i));
}
}
}
}
WSAdapter.java
// I forgot what WS stands for, but this class serves as an adapter for JSON and Online stuff
// I think it stands for With-Server Adapter
public class WSAdapter extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
static public class SendAPIRequests extends AsyncTask<String, String, String> {
// Add a pre-execute thing
#Override
protected String doInBackground(String... params) {
Log.e("TAG", params[0]);
Log.e("TAG", params[1]);
String data = "";
HttpURLConnection httpURLConnection = null;
try {
// Sets up connection to the URL (params[0] from .execute in "login")
httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
// Sets the request method for the URL
httpURLConnection.setRequestMethod("POST");
// Tells the URL that I am sending a POST request body
httpURLConnection.setDoOutput(true);
// To write primitive Java data types to an output stream in a portable way
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
// Writes out a byte to the underlying output stream of the data posted from .execute function
wr.writeBytes("postData=" + params[1]);
// Flushes the postData to the output stream
wr.flush();
wr.close();
// Representing the input stream
InputStream in = httpURLConnection.getInputStream();
// Preparing input stream bytes to be decoded to charset
InputStreamReader inputStreamReader = new InputStreamReader(in);
StringBuilder dataBuffer = new StringBuilder();
// Translates input stream bytes to charset
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
// concatenates data characters from input stream
dataBuffer.append(current);
}
data = dataBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Disconnects socket after using
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
Log.e("TAG", data);
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
Posts.PostsDetails postsHelper = new Posts().new PostsDetails();
// For posts
try {
if (postsHelper.getIsPDCalled()){
JSONObject pJObj = new JSONObject(result);
JSONArray pJObjArray = pJObj.getJSONArray("posts");
for (int i = 0; i < pJObjArray.length(); i++) {
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
postsHelper.setPost(pJObj_data.getInt("id"), "post_title", "post_content");
}
}
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
}
}
}
Yes, you can and should put the network calls functions in a separate java file for better readability and test-coverage.
Apart from that, i would suggest to use Retrofit as your HTTP client. It helps you to manage all the dirty things like headers and converters etc, so you can put all your effort on your logic and implementing your callback actions.
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 am new in android development, I want to insert call log details in MySQL database, here I have created simple ArrayAdapter that's not getting set in listview and second thing is, how to insert data in MySQL server.
Here is my java code
public class MainActivity extends Activity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.lv);
getCallDetails();
}
private void getCallDetails()
{
StringBuffer sb = new StringBuffer();
String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,null, null, strOrder);
int number1 = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type1 = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int duration1 = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Call Log :");
while (managedCursor.moveToNext())
{
final String number = managedCursor.getString(number1);
final String type2 = managedCursor.getString(type1);
final String date = managedCursor.getString(managedCursor.getColumnIndexOrThrow("date")).toString();
java.util.Date date1 = new java.util.Date(Long.valueOf(date));
final String duration = managedCursor.getString(duration1);
String type = null;
final String fDate = date1.toString();
int callcode = Integer.parseInt(type2);
switch (callcode)
{
case CallLog.Calls.OUTGOING_TYPE:
type = "Outgoing";
break;
case CallLog.Calls.INCOMING_TYPE:
type = "Incoming";
break;
case CallLog.Calls.MISSED_TYPE:
type = "Missed";
break;
}
List<DataBean> DataBeanList = new ArrayList<DataBean>();
DataBean dataBean = new DataBean(number, type, fDate, duration);
DataBeanList.add(dataBean);
Log.d("tag", DataBeanList.toString());
}
managedCursor.close();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,android.R.id.text1);
listView.setAdapter(arrayAdapter);
}
}
Here is my php script.........
<?php
//Importing our db connection script
require_once('connect.php');
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$number = $_POST['number'];
$duration = $_POST['duration'];
$type = $_POST['type'];
$time = $_POST['time'];
//Creating an sql query
$sql = "INSERT INTO call_detail (number,duration,type,time) VALUES ('$number','$duration','$type','$time')";
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Entry Added Successfully';
}else{
echo 'Could Not Add Entry';
}
//Closing the database
mysqli_close($con);
}
Well i am using this method to upload data from Android to MySQL Database. First of all you need an AsyncTask to communicate with the .php file and send the data. So i would suggest to try this:
public class MyInsertDataTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(YourActivity.this);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setIndeterminate(true);
pDialog.setMessage("Data Processing");
pDialog.setCancelable(false);
pDialog.setInverseBackgroundForced(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection urlConnection =(HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept-Encoding", "application/json");
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
setupDataToDB();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
outputStreamWriter.write(dataToWrite.toString());
Log.e("Data To Write", dataToWrite.toString());
outputStreamWriter.flush();
outputStreamWriter.close();
int responseCode = urlConnection.getResponseCode();
Log.e("Response Code ", String.valueOf(responseCode));
if (responseCode == 200){
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
StringBuilder jsonResult = inputStreamToString(inputStream, YourActivity.this);
JSONObject jsonResponse = new JSONObject(jsonResult.toString());
Log.e("Data From JSON", jsonResponse.toString());
return true;
}else{
InputStream inputStream = new BufferedInputStream(urlConnection.getErrorStream());
Log.e("ERROR STREAM", inputStream.toString());
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
if (aVoid){
Toast.makeText(YourActivity.this, "Data Sent", Toast.LENGTH_LONG).show();
YourActivity.this.finish();
}else{
Toast.makeText(YourActivity.this, "There was a problemm sending the data. Please try again", Toast.LENGTH_LONG).show();
}
}
}
private void setupDataToDB() {
JSONObject dataToWrite = new JSONObject();
try {
dataToWrite.put("number", numberStringFromJava);
dataToWrite.put("duration", durationStringFromJava);
dataToWrite.put("type", typeStringFromJava);
dataToWrite.put("time", timeStringFromJava);
} catch (JSONException e) {
e.printStackTrace();
}
}
and then your InputStreamToString method:
public StringBuilder inputStreamToString(InputStream is, Activity activity) {
String rLine;
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (Exception e) {
activity.finish();
}
return answer;
}
And this should insert the data if everything is correct. You have to execute it like this:
new MyInsertDataTask().execute("Your_php_file_path");
Hope it helps!!!
Watch these videos and learn how to insert data into online phpmyadmin server using your android app. For this, get a free web hosting server from 000webhost for creating a database online to store data and then can retrieve data online.
Simple and Interesting way to learn how to store data online on a web server.
https://www.youtube.com/watch?v=k3O3CY75ITY
This is the first part of the video.