Android Fetch Json - android

im sorry but im new at android programming, so this may seem like a very stupid question.
i've established connection to my JSON data, but i need to only fetch the data i need, and not all unnecessary data. My Json looks like this:
data":[{"id":1,"temperature":"21.375","humidity":"28"}
Here i only need id: 1, temperature: 21.375 and humidity: 28
to establish connection i have following method:
private class jsonConnection extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
String username = "websiteUsername";
String password = "websitePassword";
String credentials = username + ":" + password;
String sensorID = "1";
String api = "api";
String websiteURL = "https://" + credentials + "#website.com" + "/" + sensorID + "/" + api;
String credBase64 = Base64.encodeToString( credentials.getBytes(), Base64.DEFAULT ).replace( "\n", "" );
try {
URL url = new URL( websiteURL );
System.out.println( url );
System.out.println( credentials );
System.out.println( websiteURL );
connection = (HttpsURLConnection) url.openConnection();
String basicAuth = "Basic " + new String( encodeBase64URLSafeString( credentials.getBytes() ) );
connection.setRequestProperty( "Authorization", basicAuth );
connection.setRequestMethod( "GET" );
connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" );
connection.setRequestProperty( "Content-Language", "en-US" );
connection.setUseCaches( false );
connection.setDoInput( true );
connection.setDoOutput( true );
connection.connect();
InputStream stream = connection.getInputStream();
bufferedReader = new BufferedReader( new InputStreamReader( stream ) );
//StringBuffer buffer = new StringBuffer();
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog( MainActivity.this );
pd.setMessage( "Please wait" );
pd.setCancelable( false );
pd.show();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute( result );
if (pd.isShowing()) {
pd.dismiss();
}
ScrollingMovementMethod());
System.out.println( data );
json_string = data;
System.out.println( "json_string: " + json_string );
}
}
i imagine i have to do something like this, but i'm not sure how to continue.
try {
JSONObject parentObject = new JSONObject( data );
JSONArray parentArray = parentObject.getJSONArray( "data" );
JSONObject finalObject = parentArray.getJSONObject( 0 );
int idName = finalObject.getInt( "id" );
int tempName = finalObject.getInt( "temperature" );
int humName = finalObject.getInt( "humidity" );
String batName = finalObject.getString( "battery" );
String modeName = finalObject.getString( "mode" );
String dateName = finalObject.getString( "date_time" );
String timeName = finalObject.getString( "date_time" );
String luxName = finalObject.getString( "lux" );
System.out.println( idName + tempName + humName + batName + modeName + dateName + timeName + luxName );
} catch (JSONException e) {
e.printStackTrace();
}
I have a suspicion that it should not be data inside the parameter, but perhaps something else, and maybe that would fix it?
JSONObject parentObject = new JSONObject( data );

Related

Asynctask not updating TextView in Fragment (Android)

Currently, I am working on a project, where I have to use an Asynctask on multiple fragments. To start with, have I segregated the Asynctask from a Fragment java class, and I have created a new public Java class, where i've put the Asynctask. So far, everything works except the last part (and most important part), where the Asynctask needs to update the textviews on the fragment view.
This is the fragment Java class:
public class DataTabelFragment extends Fragment {
public TextView sensor1;
jsonAsynctask jsonasynctask = new jsonAsynctask(this);
public DataTabelFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate( R.layout.fragment_data_tabel, container, false );
sensor1 = (TextView) view.findViewById( R.id.sensor1Box );
new jsonAsynctask(this).execute();
System.out.println("HEJ MED DIG");
return view;
}
public void inExecute() {
for (int i = 0; i < jsonasynctask.allId.size(); i++) {
sensor1.append( jsonasynctask.allId.get( i ) + " | " + jsonasynctask.allDevice.get( i ) + " | " + jsonasynctask.allTemp.get( i ) + " | " + jsonasynctask.allHum.get( i ) + " | " + jsonasynctask.allBat.get( i ) + " | " + jsonasynctask.allMode.get( i ) + " | " + jsonasynctask.allLux.get( i ) + " | " + jsonasynctask.allDate_time.get( i ) + "\n\n" );
}
}
}
This is the Java Class where in the Asynctask is:
public class jsonAsynctask extends AsyncTask<Void, Void, Void> {
DataTabelFragment dataTabelFragment;
JSONObject idArray, deviceArray, tempArray, humArray, batArray, modeArray, date_timeArray, luxArray;
JSONArray json2;
String basicAuth, line, json_string, json, cxwebURL, credentials, password, username;
String data = "";
String id = "";
List<String> allId = new ArrayList<String>();
List<String> allDevice = new ArrayList<String>();
List<String> allTemp = new ArrayList<String>();
List<String> allHum = new ArrayList<String>();
List<String> allBat = new ArrayList<String>();
List<String> allMode = new ArrayList<String>();
List<String> allDate_time = new ArrayList<String>();
List<String> allLux = new ArrayList<String>();
Gson gson;
ProgressDialog pd;
//HttpsURLConnection connection;
HttpURLConnection connection;
BufferedReader bufferedReader;
URL url;
public jsonAsynctask(DataTabelFragment dataTabelFragment) {
this.dataTabelFragment = dataTabelFragment;
}
public void inBackground() {
username = "xxx";
password = "xxx";
credentials = username + ":" + password;
cxwebURL = "https://" + credentials + "#xxx.com/fetch.php?";
try {
url = new URL( cxwebURL );
connection = (HttpsURLConnection) url.openConnection();
basicAuth = "Basic " + new String( encodeBase64URLSafeString( credentials.getBytes() ) );
connection.setRequestProperty( "Authorization", basicAuth );
connection.setRequestMethod( "GET" );
connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" );
connection.setRequestProperty( "Content-Language", "en-US" );
connection.setUseCaches( false );
connection.setDoInput( true );
connection.setDoOutput( true );
connection.connect();
InputStream stream = connection.getInputStream();
bufferedReader = new BufferedReader( new InputStreamReader( stream ) );
line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
System.out.println( "PRINT DATA HER: " + data );
json2 = new JSONArray( data );
System.out.println( "DET HER ER json2" + json2 );
for (int i = 0; i < json2.length(); i++) {
idArray = json2.getJSONObject( i );
deviceArray = json2.getJSONObject( i );
tempArray = json2.getJSONObject( i );
humArray = json2.getJSONObject( i );
batArray = json2.getJSONObject( i );
modeArray = json2.getJSONObject( i );
date_timeArray = json2.getJSONObject( i );
luxArray = json2.getJSONObject( i );
id = idArray.getString( "id" );
String temp = tempArray.getString( "temp" );
String device = deviceArray.getString( "device" );
String hum = humArray.getString( "hum" );
String bat = batArray.getString( "bat" );
String mode = modeArray.getString( "mode" );
String date_time = date_timeArray.getString( "time" );
String lux = luxArray.getString( "light" );
allId.add( id );
allDevice.add( device );
allTemp.add( temp );
allHum.add( hum );
allBat.add( bat );
allMode.add( mode );
allDate_time.add( date_time );
allLux.add( lux );
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
private static String encodeBase64URLSafeString(byte[] binaryData) {
return android.util.Base64.encodeToString( binaryData, android.util.Base64.URL_SAFE );
}
#Override
protected Void doInBackground(Void... voids) {
inBackground();
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//pd = new ProgressDialog( new MainActivity() );
//pd.setMessage( "Være sød at vente" );
//pd.setCancelable( false );
//pd.show();
}
#Override
public void onPostExecute(Void result) {
super.onPostExecute( result );
/*
if (pd.isShowing()) {
pd.dismiss();
}*/
gson = new Gson();
json = gson.toJson( data );
json_string = data;
dataTabelFragment.inExecute();
}
}
it is a bad usage of asynctask in your example. In addition, don't hold your data in your asynctask class to retrieve from a fragment. Instead, you should pass your data from onPostExecute method of asynctask to the fragment. The best way is to use an asynctask would be use it with an interface and pass data via that interface. I will put an example, i hope it helps.
public class YourFragment extends Fragment implements YourAsyncTask.YourInterface {
public YourFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_your, container, false);
//do your initial things
.
.
.
YourAsyncTask yourAsyncTask = new YourAsyncTask(this);
yourAsyncTask.execute();
return view;
}
#Override
public void onJobFinishListener(YourDataType yourData) {
//when this method is trigered by your asynctask
//it means that you are in ui thread and update your ui component
//TODO: update ui component with your data
}
}
and below is an asynctask example witn an interface parameter:
public class YourAsyncTask extends AsyncTask {
private YourInterface yourInterfaceListener;
private YourDataType yourData; //this data should be calculated in doInBackground method and send via interface
public YourAsyncTask(YourInterface yourInterfaceListener) {
this.yourInterfaceListener = yourInterfaceListener;
}
#Override
protected Object doInBackground(Object[] objects) {
//do your all background tasks here
.
.
.
yourData = do something here to fill your data..
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
yourInterfaceListener.onJobFinishListener(yourData);
}
public interface YourInterface{
void onJobFinishListener(YourDataType yourData);
}
}
Edit: I didn't see above answer when i was writing this. It s also a nice example
Better make use of Interface.
I have also used in one of my project for almost same scenario.
1) Create Interface
public interface AsyncResponse {
void processFinish(String output);
}
2) Initialise interface in constructor of Async task class like you doing
public jsonAsynctask(AsyncResponse asynctaskResponse) {
this.asynctaskResponse = asynctaskResponse;
}
3) Implement interface in your fragment
new jsonAsynctask(new jsonAsynctask.AsyncResponse() {
#Override
public void processFinish(String output) {
// do whatever you want do here
}
}).execute(videouri.toString(), f.getPath());
Hope It will help.
The interface approach solution example by parliament is the best approach. I would also suggest to use a WeakReference on the private YourInterface yourInterfaceListener;
public class YourAsyncTask extends AsyncTask {
private WeakReference<YourInterface> yourInterfaceListener;
private YourDataType yourData; //this data should be calculated in doInBackground method and send via interface
public YourAsyncTask(YourInterface yourInterfaceListener) {
this.yourInterfaceListener = new WeakReference<YourInterface>(yourInterfaceListener);
}
#Override
protected Object doInBackground(Object[] objects) {
//do your all background tasks here
.
.
.
yourData = do something here to fill your data..
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
if(yourInterfaceListener.get()!=null){
yourInterfaceListener.get().onJobFinishListener(yourData);
}
}
public interface YourInterface{
void onJobFinishListener(YourDataType yourData);
}
}

Disable a Button when Activity Start

I have some value Associated to my button Which is linked with the specific field in the my database.
How to disable the button (Without Clicking) if the field is not Null.
I tried to do this :
public class MainActivity extends AppCompatActivity {
Button button;
String service_id = "65";
String indate = "29/03/2018";
String intransit = "2018-03-21 15:00:00.000";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
button = (Button) findViewById( R.id.Enter );
button.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
new Background().execute();
//new Enter().execute();
}
} );
}
private class Background extends AsyncTask<String, Void, String>{
String url;
#Override
protected String doInBackground(String... strings) {
url = "http://localhost/check.php";
try {
URL urL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urL.openConnection();
conn.setRequestMethod( "POST" );
conn.setDoInput( true );
conn.setDoOutput( true );
OutputStream out = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( out, "UTF-8" ) );
String data = URLEncoder.encode( "service_id", "UTF-8" ) + "=" + URLEncoder.encode( service_id, "UTF-8" ) + "&"
+ URLEncoder.encode( "indate", "UTF-8" ) + "=" + URLEncoder.encode( indate, "UTF-8")+ "&"
+ URLEncoder.encode( "intransit", "UTF-8" ) + "=" + URLEncoder.encode( intransit, "UTF-8");
writer.write( data );
writer.flush();
writer.close();
out.close();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader( new InputStreamReader( in, "iso-8859-1" ) );
String result = "";
String line = "";
while((line =reader.readLine()) != null){
result += line;
}
reader.close();
in.close();
conn.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result){
Log.e(TAG, "Result ="+result);
if(result.equals( "Disabled" )){
button.setEnabled( false );
}else{
Toast.makeText( MainActivity.this, "Updated", Toast.LENGTH_SHORT ).show();
button.setEnabled( false );
}
}
}
}
In this code :
Here when the Activity start the button is still enable and to disable it i have to click on it.
Please bare my English.
Thanks For any Help.
Android provides two ways to achieve the same -
1. button.setClickable(false)
Button will not respond to any click events if you use this.
2. button.setEnabled(false)
Using this is not only not clickable, but it also visually indicates that button is disabled.
And based on your null check(condition) you can easily achieve this.
Thanks.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
button = (Button) findViewById( R.id.Enter );
if(field != null) {
button.setEnabled(false); // Or use setClickable(false) if you still want to show the button as not opaque
}
button.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
new Background().execute();
//new Enter().execute();
}
} );
}
A better practise is to hide the button instead disabling it but I don't know what you have to do, so use the code above

Pull down to refresh in RecyclerView [duplicate]

This question already has answers here:
Pull to refresh recyclerview android
(7 answers)
Closed 4 years ago.
Bear my English
Whenever any data is added in my database then on refresh the data should be reflected.
And one more thing can you help me Regarding how do I create notification if any new data is Added
I am using:
1) Xampp for Apache
2) Microsoft SQL Server
This is my RecyclerActivtiy
Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_engineer_recycler );
Bundle bundle = getIntent().getExtras();
service_id = bundle.getString( "empid" );
type_id = bundle.getString( "type" );
if(type_id.equals( "pending" )){
this.setTitle( "Pending Complaint " );
}else if(type_id.equals( "history" )){
this.setTitle( "Complaint History" );
}
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat( "dd/MM/yyyy" );
String time = format.format( calendar.getTime() );
Log.e( TAG, "Time" +time );
new AsyncLogin().execute(service_id,type_id, time);
}
private class AsyncLogin extends AsyncTask<String, String, String> {
ProgressDialog pdloding = new ProgressDialog(EngineerRecycler.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute(){
super.onPreExecute();
pdloding.setMessage( "\tLoading.." );
pdloding.setCancelable( false );
pdloding.show();
}
#Override
protected String doInBackground(String... strings) {
try {
serviceid = (String) strings[0];
typeid = (String) strings[1];
time1 = (String) strings[2];
if(typeid.equals( "pending" )){
url = new URL("http://localhost/players.php");
}else if(typeid.equals( "history" )){
url = new URL("http:/localhost/StudentDetails.php");
}
} catch (MalformedURLException e) {
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream outputStream = conn.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter( outputStream, "UTF-8" ) );
String post_data = URLEncoder.encode( "serviceid","UTF-8" ) + "=" + URLEncoder.encode( serviceid, "UTF-8" ) + "&"
+URLEncoder.encode( "time1","UTF-8" ) + "=" + URLEncoder.encode( time1, "UTF-8" );
bufferedWriter.write( post_data );
bufferedWriter.flush();
bufferedWriter.close();
Log.e( TAG, "POST DATA "+post_data );
} 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) {
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){
Log.e( TAG,"result"+result );
pdloding.dismiss();
List<DataComplaint> data = new ArrayList<>( );
pdloding.dismiss();
if(result.equals( "No complaint assgin null" )){
Toast.makeText( EngineerRecycler.this, "No Complaint Assign", Toast.LENGTH_SHORT ).show();
}else{
try {
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);
DataComplaint fishData = new DataComplaint(
json_data.getString("comp_desc"),
json_data.getString("comp_reason"),
json_data.getString("ClientName"),
json_data.getString( "SiteName" ),
json_data.getString( "comp_ticketid" ));
data.add(fishData);
}
cAdapter.notifyDataSetChanged();
// Setup and Handover data to recyclerview
complaints = (RecyclerView)findViewById(R.id.complaintList);
cAdapter = new complaintAdapter(EngineerRecycler.this, data,service_id, type_id);
complaints.setAdapter(cAdapter);
complaints.setLayoutManager(new LinearLayoutManager(EngineerRecycler.this));
} catch (JSONException e) {
}
}
}
}
This the code for my Adapter
Code:
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.container_complaint, viewGroup, false);
return new MyHolder( v );
}
#Override
public void onBindViewHolder(#NonNull final MyHolder myHolder, final int i) {
final DataComplaint current=data.get(i);
myHolder.textcomplaint.setText(current.complaint);
myHolder.textaddress.setText("Reason: " + current.getAddress());
myHolder.textType.setText("Client : " + current.getComplaint_type());
myHolder.textplace.setText("Location: " + current.getLocation());
myHolder.textticket.setText( current.getTicket());
myHolder.linearLayout.setVisibility( View.GONE );
}
#Override
public int getItemCount() {
return data.size();
}
public class MyHolder extends RecyclerView.ViewHolder {
TextView textcomplaint;
TextView textaddress;
TextView textType,textplace, textticket, textreso;
Button btn, btn1, btn2;
int value1;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
LinearLayout linearLayout;
RelativeLayout relativeView;
public MyHolder(#NonNull View itemView) {
super( itemView );
textcomplaint = (TextView) itemView.findViewById( R.id.textcomplaint );
textaddress = (TextView) itemView.findViewById( R.id.textaddress );
textType = (TextView) itemView.findViewById( R.id.textType );
textticket = (TextView) itemView.findViewById( R.id.ticketid );
textplace = (TextView) itemView.findViewById( R.id.textplace );
btn = (Button) itemView.findViewById( R.id.enter );
btn1 = (Button) itemView.findViewById( R.id.repositry );
btn2 = (Button) itemView.findViewById( R.id.exit );
linearLayout = (LinearLayout) itemView.findViewById( R.id.linear_layout );
relativeView = (RelativeLayout) itemView.findViewById( R.id.view );
}
Here the problem is how implement pull down to refresh function in my recyclerview.
And Where to write function for it whether in RecyclerActivity or in Adapter.
Can anyone help me out regarding this problem.
You can wrap you RecyclerView with the SwipeRefreshLayout for making a pull to refresh.
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/refreshView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.SwipeRefreshLayout>
And you should listen to refresh events for the SwipeRefreshLayout:
refreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// Load data to your RecyclerView
refreshData();
}
});

android HttpGet/HttpPost parameters allways arrive as null to the server

I'm trying to send data to the server but it seems that I always send null values, any idea? The idea is to add a new customer through the mobile application to my database hosted in a server.
Here's my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nuevo_insert);
//etResponse = (EditText) findViewById(R.id.etResponse2);
etNombre = (EditText) findViewById(R.id.etNombre);
etApellido = (EditText) findViewById(R.id.etApellido);
etEdad = (EditText) findViewById(R.id.etEdad);
nombre = etNombre.getText().toString();
apellido = etApellido.getText().toString();
edad = etEdad.getText().toString();
}
public void insertar(View view) {
// Call AsyncTask to perform network operation on separate thread
// working in localhost you CAN'T put localhost in that address, you
// MUST put your IP address or it will crush
new HttpAsyncTask().execute("http://192.168.1.34/android/insertCustomer.php");
}
public static String GET(String url) {
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpClient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpClient.execute(new HttpGet(url+ "?nombre=" + nombre + "&apellido=" + apellido + "&edad="+ edad));
// receive response as InputStream
inputStream = httpResponse.getEntity().getContent();
// convert InputStream to string
if (inputStream != null) {
result = convertInputStreamToString(inputStream);
} else {
result = "No ha funcionat!";
}
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask
#Override
protected void onPostExecute(String result) {
String s = "";
Toast.makeText(getBaseContext(),getResources().getString(R.string.rebut), Toast.LENGTH_LONG).show();
JSONArray jArray;
try {
jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = jArray.getJSONObject(i);
s = s + "Nom: " + json.getString("FirsName") + " "
+ json.getString("LastName") + "\n" + "Edat: "+ json.getInt("Age") + "\n\n";
}
etResponse.setText(s);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is my php file:
<?php
$con = mysql_connect('localhost', 'root', '');
if(!$con){
die("No se ha podido realizar la conexion: ".mysql_error());
}
mysql_select_db("TestDatabase", $con);
$nombre = $_GET['nombre'];
$apellido = $_GET['apellido'];
$edad = $_GET['edad'];
print_r($nombre."-".$apellido."-".$edad);
$result = mysql_query("insert into customer(FirsName, LastName, Age) values ('$nombre', '$apellido', '$edad')");
mysql_close($con);
?>
OK the problem was that I was retrieving the data from EditText boxes in the onCreate and I had to do it in the GET method :-)
If you are getting null value means that mean u r passing wrong type parameters or url may be wrong you do check it out
Change
HttpResponse httpResponse = httpClient.execute(new HttpGet(url+ "?nombre=" + nombre + "&apellido=" + apellido + "&edad="+ edad));
to this:
String request = url+ "?nombre=" + nombre + "&apellido=" + apellido + "&edad="+ edad;
Log.d("DEBUG", request);
HttpResponse httpResponse = httpClient.execute(request);
and see your logcat for your url, maybe it is broken.
if the url is ok, then try opening this url in your browser and check the results.

send post data android to php not working [duplicate]

This question already exists:
send post android to php not working [closed]
Closed 9 years ago.
I have a problem I want to send
Email and the name and phone to the server php at the same time
Is there a solution
On which I work is at the bottom
........................................................
public class MainActivity extends Activity {
EditText name;
EditText email;
EditText tlf;
Button btn;
string resultat=null;
InputStream is = null;
StringBuilder sb = null ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
name= (EditText)findViewById(R.id.name);
email = (EditText)findViewById(R.id.email);
tlf = (EditText)findViewById(R.id.tlf);
btn = (Button)findViewById(R.id.btn);
}
public void envoyerMessage (View v){
HttpClient client= new DefaultHttpClient();
HttpPost post=new HttpPost("http://xxxxcom/app.php");
String nam = name.getText().toString();
String mail = email.getText().toString();
String fon = tlf.getText().toString();
if(log.length() >0){
try {
List<NameValuePair> donnees = new ArrayList<NameValuePair>(1);
donnees.add(new BasicNameValuePair("id", nam ));
donnees.add(new BasicNameValuePair("mal", mail ));
donnees.add(new BasicNameValuePair("fn", fon ));
post.setEntity(new UrlEncodedFormEntity(donnees));
client.execute(post);
login.setText("");
Toast.makeText(this, "valid login", Toast.LENGTH_SHORT).show();
Thanks
My suggestion is use Volley, here is a very mini sample:
https://github.com/ogrebgr/android_volley_examples/blob/master/src/com/github/volley_examples/Act_SimpleRequest.java
A Jar to Volley.
But you could try this Util:
public static class Connector extends AsyncTask<String, Object, Object> {
private static final int DEFAULT_CNN_TIME_OUT = 1000 * 20;
private static String USER_AGENT;
private String mUrl;
private byte[] mBody;
public Connector( Context _cxt ) {
super();
if( TextUtils.isEmpty( USER_AGENT ) ) {
// Without this, the default provided by API will be like "Dalvik/1.6.0 (Linux; U; Android 4.0.4; BASE_Lutea_3 Build/IMM76D)" .
USER_AGENT = new WebView( _cxt ).getSettings().getUserAgentString();
}
}
/*
* Convenient function to execute the connecting task.
*/
public void submit( String _url ) {
this.execute( _url );
}
#Override
protected Object doInBackground( String... _params ) {
mUrl = _params[0];
Object ret = null;
HttpURLConnection conn = null;
try {
synchronized( Connector.class ) {
InputStream in = null;
conn = connect( mUrl );
// if we don't do conn.setRequestProperty( "Accept-Encoding", "gzip" ), the wrapper GZIPInputStream can be removed.
onConnectorInputStream( in = new GZIPInputStream( conn.getInputStream() ) );
in.close();
in = null;
}
}
catch( Exception _e ) {
ret = _e;
}
finally {
if( conn != null ) {
conn.disconnect();
conn = null;
}
}
return ret;
}
#Override
protected void onPostExecute( Object _result ) {
if( _result instanceof SocketTimeoutException ) {
onConnectorConnectTimout();
} else if( _result instanceof ConnectorPostConnectException ) {
onConnectorError( ((ConnectorPostConnectException) _result).getStatus() );
} else if( _result instanceof Exception ) {
onConnectorInvalidConnect( (Exception) _result );
} else if( _result == null ) {
onConnectorFinished();
}
handleEstablishedConnection();
}
/*
* Internal help and test function.
*/
private static void handleEstablishedConnection() {
try {
Log.v( TAG, "Connection is established." );
CookieStore cs = CookieManager.getInstance().getCookieStore();
if( cs != null ) {
Log.v( TAG, "------------cookies------------" );
List<Cookie> list = cs.getCookies();
if( list != null && list.size() > 0 ) {
StringBuilder cookieBuilder = new StringBuilder();
for( Cookie c : list ) {
cookieBuilder
.append( c.getName().trim() )
.append( "=>" )
.append( c.getValue().trim() )
.append( "=>" )
.append( c.getDomain() );
Log.v( TAG, cookieBuilder.toString() );
cookieBuilder.delete( 0, cookieBuilder.length() - 1 );
}
cookieBuilder = null;
} else {
Log.v( TAG, "Empty cookies." );
}
cs = null;
list = null;
}
}
catch( Exception _e ) {
Log.e( TAG, "Error in handleEstablishedConnection: " + _e.getMessage() );
}
finally {
}
}
private HttpURLConnection connect( String _urlStr ) throws Exception {
URL url = null;
HttpURLConnection conn = null;
try {
try {
url = new URL( _urlStr );
}
catch( MalformedURLException e ) {
throw new IllegalArgumentException( "Invalid url: " + _urlStr );
}
conn = preConnect( url );
doConnect( conn );
conn = postConnect( conn );
}
catch( Exception _e ) {
throw _e;
}
finally {
url = null;
}
return conn;
}
private HttpURLConnection preConnect( URL url ) throws Exception {
HttpURLConnection conn;
conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches( false );
// http://www.aswinanand.com/2009/01/httpurlconnectionsetfollowredirects-bug/comment-page-1/#comment-13330
// see the url to learn more about the problem of redirect
conn.setInstanceFollowRedirects( false );
conn.setDoOutput( true );// allows body
mBody = getBody();
if( hasBody() ) {
conn.setFixedLengthStreamingMode( mBody.length );
}
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Connection", "Keep-Alive" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded;charset=UTF-8" );
conn.setRequestProperty( "User-Agent", USER_AGENT );
conn.setRequestProperty( "Accept-Encoding", "gzip" );// force server to send in Content-Encoding: gzip .
String cookies = onCookie();
if( !TextUtils.isEmpty( cookies ) ) {
conn.setRequestProperty( "Cookie", onCookie() );
cookies = null;
}
conn.setConnectTimeout( onSetConnectTimeout() );
return conn;
}
/*
* Convenient function to check the exiting of body.
*/
private boolean hasBody() {
return mBody != null && mBody.length > 0;
}
private void doConnect( HttpURLConnection conn ) throws Exception {
OutputStream out; // the outgoing stream
out = conn.getOutputStream();
if( hasBody() ) {
out.write( mBody );
}
out.close();
out = null;
}
private HttpURLConnection postConnect( HttpURLConnection conn ) throws Exception {
int status = conn.getResponseCode();
if( status != HttpURLConnection.HTTP_OK ) {
throw new ConnectorPostConnectException( status );
} else {
CookieManager.getInstance().put( conn.getURL().toURI(), conn.getHeaderFields() );
return conn;
}
}
private byte[] getBody() {
byte[] body = null;
String bodyString = onSetBody();
if( !TextUtils.isEmpty( bodyString ) ) {
body = bodyString.getBytes();
}
return body;
}
// ------------------------------------------------
// Overrides methods here
// ------------------------------------------------
protected int onSetConnectTimeout() {
return DEFAULT_CNN_TIME_OUT;
}
protected String onCookie() {
return null;
}
protected String onSetBody() {
return null;
}
protected void onConnectorConnectTimout() {
Log.e( TAG, "Handling connector timeout gracefully." );
}
protected void onConnectorError( int _status ) {
Log.e( TAG, "Handling connector error(responsed) gracefully: " + _status );
}
protected void onConnectorInvalidConnect( Exception _e ) {
Log.e( TAG, "Handling connector invalid connect(crash) gracefully: " + _e.toString() );
}
/*
* Read data here. The function runs in thread. To hook on UI thread use onConnectorFinished()
*/
protected void onConnectorInputStream( InputStream _in ) {
}
/*
* Last handler for a success connection
*/
protected void onConnectorFinished() {
}
}
Use this util:
mConn = new Util.Connector( getApplicationContext() ) {
#Override
protected String onSetBody() {
String body = null;
try {
StringBuilder bodyBuilder = new StringBuilder();
bodyBuilder
.append( "id=" )//.append(...)
.append( '&' )
.append( "mal=" )//.append(...)
body = bodyBuilder.toString();
bodyBuilder = null;
}
catch( Exception _e ) {
Log.e( TAG, "Error in onCreateBody: " + _e.getMessage() );
}
finally {
}
return body;
}
#Override
protected int onSetConnectTimeout() {
return 10 * 1000;
}
#Override
protected void onConnectorInvalidConnect( Exception _e ) {
super.onConnectorInvalidConnect( _e );
onErr();
}
#Override
protected void onConnectorError( int _status ) {
super.onConnectorError( _status );
onErr();
}
protected void onConnectorConnectTimout() {
super.onConnectorConnectTimout();
onErr();
}
private void onErr() {
//mConn.submit( URL );
};
#Override
protected void onConnectorFinished() {
}
#Override
protected void onConnectorInputStream( InputStream _in ) {
}
};
mConn.submit( URL );

Categories

Resources