can someone help me plsss, the error message comes in the textbox on the login form, the error is when i submit my information on the first form it won't go to database instead showing error "error java.net.socketException: permission denied" here's my code:
tambah_user.java
package com.wilis.hellomysql;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
public class tambah_user extends Activity {
EditText un,pw,rpw,nl,al,nt,nh;
RadioGroup jk;
TextView error;
Button simpan,keluar;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tambah_user);
un=(EditText)findViewById(R.id.et_un);
pw=(EditText)findViewById(R.id.et_pw);
rpw=(EditText)findViewById(R.id.et_rpw);
nl=(EditText) findViewById(R.id.et_nama);
jk=(RadioGroup) findViewById(R.id.jekel);
al=(EditText) findViewById(R.id.et_alamat);
nt=(EditText) findViewById(R.id.et_notel);
nh=(EditText) findViewById(R.id.et_nohp);
simpan=(Button)findViewById(R.id.btn_simpan);
keluar=(Button)findViewById(R.id.btn_keluar);
error=(TextView)findViewById(R.id.error);
simpan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//atur variabel utk menampung pilihan jenis kelamin
String type=null;
switch (jk.getCheckedRadioButtonId()) {
case R.id.pria:
type="Pria";
break;
case R.id.perempuan:
type="Perempuan";
break;
}
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
postParameters.add(new BasicNameValuePair("repassword", rpw.getText().toString()));
postParameters.add(new BasicNameValuePair("nama", nl.getText().toString()));
postParameters.add(new BasicNameValuePair("jekel", type));
postParameters.add(new BasicNameValuePair("alamat", al.getText().toString()));
postParameters.add(new BasicNameValuePair("nomor_tlp", nt.getText().toString()));
postParameters.add(new BasicNameValuePair("nomor_hp", nh.getText().toString()));
/* String valid = "1";*/
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/appmysql/simpan.php", postParameters);
String res = response.toString();
res = res.trim();
res = res.replaceAll("\\s+","");
error.setText(res);
if (res.equals("1")) error.setText("Data Tersimpan");
else error.setText("Data Tersimpan Ke server");
}
catch (Exception e) {
un.setText(e.toString());
}
}
});
}
public void keluar (View theButton)
{
}
}
CustomHttpClient.java
package com.wilis.hellomysql;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class CustomHttpClient {
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
private static HttpClient mHttpClient;
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
tambah_user.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff00ffff"
>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:text="Silakan Masukkan Data Pengguna"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#ff0000ff"
/>
<TableRow android:baselineAligned="true" android:layout_width="match_parent">
<TextView
android:text="Username:"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:id="#+id/et_un"
android:maxWidth="140sp"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_gravity="center_vertical" >
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="Password:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:id="#+id/et_pw"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_gravity="center_vertical"
android:inputType="textPassword">
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="retype-Password:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_rpw"
android:layout_width="match_parent"
android:inputType="textPassword">
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="Nama Lengkap:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_nama"
android:layout_width="match_parent">
</EditText>
</TableRow>
<TableRow>
<TextView android:text="Jekel:"
android:textColor="#ff0000ff"/>
<RadioGroup android:id="#+id/jekel">
<RadioButton android:id="#+id/pria"
android:text="Pria"
/>
<RadioButton android:id="#+id/perempuan"
android:text="Perempuan"
/>
</RadioGroup>
</TableRow>
<TableRow>
<TextView
android:text="Alamat:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_alamat"
android:layout_width="match_parent">
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="Nomor Tlp:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_notel"
android:layout_width="match_parent">
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="Nomor HP:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_nohp"
android:layout_width="match_parent">
</EditText>
</TableRow>
<TableRow >
<Button android:text="S I M P A N"
android:id="#+id/btn_simpan"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<Button android:text="K E L U A R"
android:id="#+id/btn_keluar"
android:onClick="keluar"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</TableRow>
<TextView
android:text=""
android:id="#+id/error"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
</TableLayout>
</ScrollView>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wilis.hellomysql"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".tambah_user"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".CustomHttpClient" android:label="#string/app_name">
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>
You have to add the internet permission to you manifiest file:
<uses-permission android:name="android.permission.INTERNET" />
And also Android wont let you do http connections in the main thread, for more info look up:
http://developer.android.com/reference/android/os/AsyncTask.html
You have forgotten the internet permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
After that you will get an networkonmainthreadexception because you are doing web request in the main thread.
Use another AsyncTask or another thread for that.
You did forget too add
<uses-permission android:name="android.permission.INTERNET" />
in your manifest.xml.
But after that you will receive a networkmainthreadexception, to avoid this you need to use AsyncTask or an extra thread. If you get problems to use this things you read this post which may helps you.
Related
I want to show logo from json but it doesn't work. Check my code and inform me about the bug. Else app name and description working fine. They only problem is that it now showing logo. Json is passing the link of that logo. I also use Glide but it doesn't work for me. I done all thing to fix it but i am unable for fix it. All code related to this is below. Please have a look at it
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import androidx.appcompat.app.AppCompatActivity;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
public class BrandshaperActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_brandshaper);
new ParseTask().execute();
}
private class ParseTask extends AsyncTask<Void, Void, String> {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String resultJson = "";
#Override
protected String doInBackground(Void... params) {
try {
String $url_json = "https://myapi.ga";
URL url = new URL($url_json);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
resultJson = buffer.toString();
Log.d("FOR_LOG", resultJson);
} catch (Exception e) {
e.printStackTrace();
}
return resultJson;
}
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
final ListView lView = (ListView) findViewById(R.id.lvMain);
String[] from = {"app_name","desc","app_logo"};
int[] to = {R.id.app_name,R.id.desc,R.id.app_logo};
ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> hashmap;
try {
JSONObject json = new JSONObject(strJson);
JSONArray jArray = json.getJSONArray("offers");
for (int i = 0; i < jArray.length(); i++) {
JSONObject friend = jArray.getJSONObject(i);
String appname = friend.getString("name");
String description = friend.getString("description");
String applogo = friend.getString("icon");
Picasso.get().load(arrayList.get(position).getThumbnailUrl(applogo)).into(app);
hashmap = new HashMap<String, String>();
hashmap.put("app_name", "" + appname);
hashmap.put("desc", "" + description);
arrayList.add(hashmap);
}
final SimpleAdapter adapter = new SimpleAdapter(BrandshaperActivity.this, arrayList, R.layout.brandshaper_item,from , to);
lView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#FFF"
android:gravity="left">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginRight="4dp"
android:layout_marginLeft="4dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="12dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_gravity="center"
android:orientation="horizontal">
<ImageView
android:id="#+id/app_logo"
android:layout_width="50dp"
android:layout_height="50dp"
android:paddingStart="3dp"
android:src="#drawable/img_bigcash">
</ImageView>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/app_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/avenirblack"
android:text="BigCash"
android:gravity="center"
android:textColor="#color/black"
android:textSize="18dp" />
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/montserrat_regular"
android:text="Install & Sign up to 200 coins"
android:gravity="center"
android:textColor="#color/black"
android:textSize="12dp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="end">
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:src="#drawable/arrow"></ImageView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/lvMain"
android:layout_width="368dp"
android:layout_height="495dp"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp" />
</RelativeLayout>
I have research on this about how to post a request and receive response from server concurrently which I finally got to some reasonable walk-through but it is not working. Please kindly help.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
process();
} catch(Exception ex){
Log.e("Url Error Encoding", "Url Error Encoding");
}
}
});
}
public void process() throws UnsupportedEncodingException{
Prog = spinner1.getSelectedItem().toString();
Dept = spinner2.getSelectedItem().toString();
Session = spinner3.getSelectedItem().toString();
Semester = spinner4.getSelectedItem().toString();
Level = spinner5.getSelectedItem().toString();
Matric = matric.getText().toString();
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
College = sharedPreferences.getString(Config.COLLEGE_SHARED_PREF,"Not Available");
// Toast.makeText(ProfileActivity.this, Matric + College, Toast.LENGTH_SHORT).show();
// content.setText(Prog);
String data = URLEncoder.encode("program", "UTF-8")
+ "=" + URLEncoder.encode(Prog, "UTF-8");
data += "&" + URLEncoder.encode("dept", "UTF-8") + "="
+ URLEncoder.encode(Dept, "UTF-8");
data += "&" + URLEncoder.encode("session", "UTF-8") + "="
+ URLEncoder.encode(Session, "UTF-8");
data += "&" + URLEncoder.encode("semester", "UTF-8") + "="
+ URLEncoder.encode(Semester, "UTF-8");
data += "&" + URLEncoder.encode("level", "UTF-8") + "="
+ URLEncoder.encode(Level, "UTF-8");
data += "&" + URLEncoder.encode("college", "UTF-8") + "="
+ URLEncoder.encode(College, "UTF-8");
data += "&" + URLEncoder.encode("matric", "UTF-8") + "="
+ URLEncoder.encode(Matric, "UTF-8");
String text = "";
BufferedReader reader=null;
try{
//Send data
URL url = new URL("http://www.example.com/locator/checkresult.php");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
} catch(Exception ex){
ex.printStackTrace();
}
finally {
try
{
reader.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
// Show response on activity
content.setText(text);
}
My php code
<?php
mysql_connect("localhost", "root", "zzz") or die(mysql_error());
mysql_select_db("sis");
$conn = mysql_connect("localhost", "root", "zzz");
$college = urldecode($_POST['college']);
$program = urldecode($_POST['program']);
$level = urldecode($_POST['level']);
$department = urldecode($_POST['dept']);
$semester = urldecode($_POST['semester']);
$session = urldecode($_POST['session']);
$matric = urldecode($_POST['matric']);
print "$program $level $department";
?>
//My profile.xml
<?xml version="1.0" encoding="UTF-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10dp">
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Large Text" android:id="#+id/textView" android:layout_marginBottom="20dp" />
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:id="#+id/textView2" android:layout_marginBottom="20dp" />
<TableLayout android:id="#+id/table" android:layout_width="wrap_content" android:layout_height="25dp" android:focusableInTouchMode="true" android:focusable="true" />
<TextView android:id="#+id/content" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="5dp" />
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Program" android:layout_marginBottom="5dp" />
<Spinner android:id="#+id/programme" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#fff" android:layout_marginBottom="10dp" />
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Level" android:layout_marginBottom="5dp" />
<Spinner android:id="#+id/level" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#fff" android:layout_marginBottom="10dp" />
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Department" android:layout_marginBottom="5dp" />
<Spinner android:id="#+id/dept" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#fff" android:layout_marginBottom="10dp" />
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Semester" android:layout_marginBottom="5dp" />
<Spinner android:id="#+id/semester" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#fff" android:layout_marginBottom="10dp" />
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Session" android:layout_marginBottom="5dp" />
<Spinner android:id="#+id/session" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#fff" android:layout_marginBottom="10dp" />
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="8dp" android:textStyle="bold" android:text="Enter your matric number" />
<EditText android:id="#+id/rmatric" android:layout_width="match_parent" android:layout_height="50dp" />
<Button android:id="#+id/checkresult" android:layout_width="match_parent" android:layout_height="match_parent" android:text="Check Result" />
</LinearLayout>
</ScrollView>
Please kindly help. Thanks.
Here is your example code
your php file
<?php
$val =file_get_contents('php://input');
$jsonObj = json_decode($val);
$jsonObj = (object)$jsonObj;
$data1 = $jsonObj->yourkey;
$data2 = $jsonObj->yourkey;
// your sql execution
$returnData = array(
"code" => 500,
"msg" => "UserName Already Exist!! Try with diffrent user Name!!",
);
$a = json_encode($returnData);
echo $a;
die();
?>
here is some java code
//fill your json object with key and value pairs
JSONObject object=new JSONObject();
try {
object.put("key", value);
object.put("key", value);
}catch (JSONException e){}
// make a request this should run on ui thred
String urlString = "";
RestHelper restHelper = new RestHelper(context);
RequestFuture requestFuture = RequestFuture.newFuture();
response = restHelper.postRequestTest(urlString,object,requestFuture);
System.out.println("Json Data" + response.toString() );
//libraries need to compile
compile 'com.mcxiaoke.volley:library:1.0.19'
compile 'com.google.code.gson:gson:2.3'
Here is RestHelper.java
import android.content.Context;
import android.graphics.Bitmap;
import android.widget.ImageView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.RequestFuture;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.naitiks.helpme.Model.HappyMomentsModel;
import com.naitiks.helpme.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
/**
* Created by Naitik on 25-04-2016.
*/
public class RestHelper {
private RequestQueue queue = null;
private Context context = null;
public void setQueue(RequestQueue queue) {
this.queue = queue;
}
public RequestQueue getQueue() {
return queue;
}
public RestHelper(Context context){
this.context = context;
queue= Volley.newRequestQueue(context);
}
public JSONObject postRequestTest(String url, final JSONObject userMap,final RequestFuture requestFuture){
JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url, userMap,requestFuture,requestFuture);
postRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 40000;
}
#Override
public int getCurrentRetryCount() {
return 5;
}
#Override
public void retry(VolleyError volleyError) throws VolleyError {
}
});
queue.add(postRequest);
try {
Object object = requestFuture.get();
System.out.println("*** result" +object.toString());
JSONObject result = (JSONObject)object;
return result;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}
}
Why you dont try with volley library and another thing i would like to suggest is use json instead of sending data with url encode.
This is just suggestion.
i'm kind a new to Android, MySQL and PHP. I'm having problem with my project in register page. When i input name and ID value and hit save button, my data is in mysql database, but when i fill the same name and password again and hit save, it's says Data saved to server, instead of error -> if (res.equals("1")) error.setText("Error"). Is anybody got any clue? Thanks.
Here's my code:
register.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TableLayout
android:layout_width="311dp"
android:layout_height="fill_parent"
android:layout_marginLeft="25dp"
android:layout_marginTop="25dp" >
<TextView
android:text="Registration"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="25dp"
/>
<TextView
android:text=""
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="20dp"
/>
<TableRow android:baselineAligned="true" android:layout_width="match_parent">
<TextView
android:text="Name :"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15dp"
/>
<EditText android:id="#+id/edtname"
android:maxWidth="180sp"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_gravity="center_vertical" >
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="ID no :"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
/>
<EditText android:id="#+id/edtid"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_gravity="center_vertical"
android:inputType="textPassword">
</EditText>
</TableRow>
<TableRow>
</TableRow>
<TextView
android:text=""
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="20dp"
/>
<TableRow
android:gravity="center"
android:layout_width="match_parent">
<Button android:text="SAVE"
android:id="#+id/btnsave"
android:layout_width="wrap_content"
android:onClick="next"
android:layout_height="wrap_content">
</Button>
<Button android:text="BACK"
android:id="#+id/btnback"
android:onClick="back"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</TableRow>
<TextView
android:text=""
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="20dp"
/>
<TextView
android:text=""
android:id="#+id/error"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
android:textSize="20dp"
/>
</TableLayout>
</ScrollView>
Register.java
package com.example.m_vote;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
public class Register extends Activity {
EditText nm,id;
TextView error;
Button save,back;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
nm=(EditText)findViewById(R.id.edtname);
id=(EditText)findViewById(R.id.edtid);
save=(Button)findViewById(R.id.btnsave);
back=(Button)findViewById(R.id.btnback);
error=(TextView)findViewById(R.id.error);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
//TODO Auto-generated method stub
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("name", nm.getText().toString()));
postParameters.add(new BasicNameValuePair("id", id.getText().toString()));
/* String valid = "1";*/
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/appmysql/data.php", postParameters);
String res = response.toString();
res = res.trim();
res = res.replaceAll("\\s+","");
error.setText(res);
if (res.equals("1")) error.setText("Error");
else
{
error.setText("Registration complete! ");
}
}
catch (Exception e) {
id.setText(e.toString());
}
}
});
}
public void back (View theButton)
{
Intent a = new Intent (this,Mainmenu.class);
startActivity(a);
}
}
CustomHttpClient.java
package com.example.m_vote;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* #param url The web address to post the request to
* #param postParameters The parameters to send via the request
* #return The result of the request
* #throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Performs an HTTP GET request to the specified url.
*
* #param url The web address to post the request to
* #return The result of the request
* #throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
data.php
<?php
$nm=$_POST['name'];
$id=$_POST['id'];
$conn = mysql_connect("localhost","root","");
mysql_select_db("projek1");
$query = "INSERT INTO user (ID,name) values ('$id','$nm')";
$result = mysql_query($query) or die("REPORTGagal Query Simpan KRS.");
if (mysql_num_rows($result) == 1){
echo 1;
}
else {
// print status message
echo 0;
}
?>
I am trying to send some commands over telnet.
Everything works fine when executed locally on a PC on basis of a swing GUI, but when using the same code on Android, the app freezes for a few seconds and the commands are not carried out (same result on emulator and real device), although it runs to the end. No error message is being thrown, but after this procedure the device is not reachable via Telnet, not even via PC (restart of target device is then necessary). What I do not understand is that it seems that the 500 milliseconds restriction I set is being ignored on Android.
I am a novice on Android so please bear with me. Glad for any help.
package com.test.test.remote;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.util.Log;
import android.view.View;
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);
}
public void calculate(View view) throws Exception {
System.out.println("Calc button executed");
command("MO");
}
public String command(String cmd) {
String output = "test";
Log.e("Msg", "command reached");
Log.e("Msg", cmd);
Socket pingSocket = null;
PrintWriter out = null;
BufferedReader in = null;
pingSocket = new Socket();
try {
pingSocket.connect(new InetSocketAddress("10.10.10.107", 23), 500);
out = new PrintWriter(pingSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
pingSocket.getInputStream()));
out.println(cmd);
output = in.readLine();
out.close();
in.close();
pingSocket.close();
System.out.println(output);
Log.e("Msg", "end of command reached");
} catch (Exception e) {
Log.e("com.example.test.MainActivity", e.getMessage());
e.printStackTrace();
}
return output;
}
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="24dp"
android:layout_marginTop="31dp"
android:ems="10"
android:inputType="numberDecimal|numberSigned" >
<requestFocus />
</EditText>
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:layout_marginTop="28dp" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/kmh" />
</RadioGroup>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/radioGroup1"
android:layout_centerVertical="true"
android:onClick="calculate"
android:text="#string/calc" />
</RelativeLayout>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.test.remote"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
My app has no error line, but when i run on emulator, it comes with an error the application Koperasidb (process.com.randy.koperasidb) has stopped unexpectedly Please try again please help, here's my login.java code:
package com.randy.koperasidb;
import android.app.Activity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class login extends Activity implements OnClickListener{
EditText kode,pw;
TextView error;
Button login;
String i;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
kode = (EditText) findViewById(R.id.kode);
pw = (EditText) findViewById (R.id.password);
login = (Button) findViewById (R.id.login);
error = (EditText) findViewById (R.id.error);
login.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.login:
insert();
}
}
public void insert(){
String i= "http://10.0.2.2/mysql/insert.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(i);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("kode", kode.getText().toString()));
param.add(new BasicNameValuePair("password", pw.getText().toString()));
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpRespose = httpClient.execute(httpPost);
HttpEntity httpEntity = httpRespose.getEntity();
InputStream in = httpEntity.getContent();
BufferedReader read = new BufferedReader(new InputStreamReader(in));
String isi= "";
String baris= "";
while((baris = read.readLine())!=null){
isi+= baris;
}
if(!isi.equals("null")){
Toast.makeText(this, "Berhasil", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "Gagal", Toast.LENGTH_LONG).show();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
here's my login.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff00ffff"
>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:text="Selamat datang di Puskopdit Jakarta"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<TextView
android:text="Input Kode Anggota"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText
android:id="#+id/kode"
android:layout_width="150px"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center"
android:hint="Kode Anggota"
/>
<TextView
android:text="Input Password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText
android:id="#+id/password"
android:layout_width="150px"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center"
android:hint="Password"
/>
<Button
android:id="#+id/login"
android:layout_width="200px"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center"
android:textColor="#ffffffff"
/>
<TextView
android:text=""
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
android:id="#+id/error"
/>
</TableLayout>
</LinearLayout>
and here's my AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.randy.koperasidb"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".login"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="9" />
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>