Here's my code for when i trying to register user and need a toast which is response from server regarding user already exist. i can post successfully to server using json but if there's response i have to idea how to catch it the image shows example when using postman.
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
private EditText signupInputName, signupInputEmail, signupInputPassword, retypeInputPassword;
private Button btnSignUp;
private Button btnLinkLogin;
private String message = "";
private int code = 0;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
signupInputName = (EditText) findViewById(R.id.signup_input_name);
signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
retypeInputPassword = (EditText) findViewById(R.id.signup_retype_password);
btnSignUp = (Button) findViewById(R.id.btn_signup);
btnLinkLogin = (Button) findViewById(R.id.btn_link_login);
btnSignUp.setOnClickListener(this);
btnLinkLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(i);
}
});
}
public String POST(String url, Person person)
{
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httppost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("user_name", person.getUsername());
jsonObject.accumulate("email", person.getEmail());
jsonObject.accumulate("password", person.getPassword());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httppost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httppost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Error! email exist";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
#Override
public void onClick(View view) {
if(validate() == 1)
{
Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
}
else if (validate() == 2)
{
Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
}
else if (validate() == 3)
{
Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
}
else if (validate() == 4)
{
//Toast.makeText(getBaseContext(), "Success", Toast.LENGTH_SHORT).show();
new HttpAsyncTask().execute("http://ip-addressses/api/register");
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls) {
person = new Person();
person.setUsername(signupInputName.getText().toString());
person.setEmail(signupInputEmail.getText().toString());
person.setPassword(signupInputPassword.getText().toString());
return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
JSONObject jObject;
try {
jObject = new JSONObject(result);
if (jObject.has("error")) {
String aJsonString = jObject.getString("error");
Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
private int validate() {
if(signupInputName.getText().toString().trim().equals("") || signupInputEmail.getText().toString().trim().equals("") || signupInputPassword.getText().toString().trim().equals("") || retypeInputPassword.getText().toString().trim().equals(""))
{
code = 1;
message = "Complete the form!";
}
else if (!(signupInputPassword.getText().toString().equals(retypeInputPassword.getText().toString())))
{
code = 2;
message = "Re-check password";
}
else if (!isValidEmail(signupInputEmail.getText().toString()) ) {
code = 3;
message = "Invalid email";
}
else
code = 4;
return code;
}
public final static boolean isValidEmail(String target)
{
if (target == null) {
return false;
} else {
Matcher match = Patterns.EMAIL_ADDRESS.matcher(target);
return match.matches();
}
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
Postman response when email exist
Just change this code:
jObject = new JSONObject(result);
if (jObject.has("error"))
{
String aJsonString = jObject.getString("error");
Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
Toast.makeText(getBaseContext(),result+"" , Toast.LENGTH_SHORT).show();
}
So by this code, if your response is not JSON it will throw exception in catch. And here you can show toast.
Related
I'm using AsyncTask to insert, update and delete data from database. I used this code to insert, update, delete and it works fine. But when I want to use select, and show the data at EditText, I can't get the value from doInBackground() to the onPostExecute() and it shows nothing.
Here's my code :
MenuUtama.java
public class MenuUtama extends Activity {
/** Called when the activity is first created. */
private TextView nama_user;
private String nm_user = "";
private EditText kode, nama, harga, deskripsi;
private Button insert, update, delete, cek;
private String kode1, nama1, harga1, deskripsi1;
JSONArray data = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
kode = (EditText) findViewById(R.id.editKode);
nama = (EditText) findViewById(R.id.editNama);
harga = (EditText) findViewById(R.id.editHarga);
deskripsi = (EditText) findViewById(R.id.editDes);
cek = (Button) findViewById(R.id.btnCek);
insert = (Button) findViewById(R.id.buttonInsert);
update = (Button) findViewById(R.id.buttonUpdate);
delete = (Button) findViewById(R.id.buttonDelete);
nama_user = (TextView) findViewById(R.id.textView3);
Intent i = getIntent();
nm_user = i.getStringExtra("nama_user");
nama_user.setText(nm_user);
insert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "";
url = "http://192.168.1.10/crudsederhana/aksi.php";
try {
String ko = URLEncoder.encode(kode.getText().toString(),"utf-8");
String n = URLEncoder.encode(nama.getText().toString(),"utf-8");
String hr = URLEncoder.encode(harga.getText().toString(),"utf-8");
String d = URLEncoder.encode(deskripsi.getText().toString(), "utf-8");
url += "?a=insert&kd=" + ko + "&nm=" + n + "&hrg=" + hr + "&deskripsi=" + d;
new CRUD().execute(url);
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
update.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url = "";
url = "http://192.168.1.10/crudsederhana/aksi.php";
try {
String ko = URLEncoder.encode(kode.getText().toString(),"utf-8");
String n = URLEncoder.encode(nama.getText().toString(),"utf-8");
String hr = URLEncoder.encode(harga.getText().toString(),"utf-8");
String d = URLEncoder.encode(deskripsi.getText().toString(), "utf-8");
url += "?a=update&kd=" + ko + "&nm=" + n + "&hrg=" +hr+ "&des=" + d;
new CRUD().execute(url);
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "";
kode1 = kode.getText().toString();
url = "http://192.168.1.10/crudsederhana/aksi.php?a=delete&kd=" + kode1;
new CRUD().execute(url);
}
});
cek.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "";
kode1 = kode.getText().toString();
url = "http://192.168.1.10/crudsederhana/aksi.php?a=read&kd="+kode1;
new CRUD().execute(url);
}
});
}
public class CRUD extends AsyncTask<String, String, String> {
String success;
String kode_d, nama_d, harga_d, des_d;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(params[0]);
try {
success = json.getString("success");
Log.e("error", "nilai sukses=" + success);
JSONArray hasil = json.getJSONArray("login");
if (success.equals("1")) {
for (int i = 0; i < hasil.length(); i++) {
JSONObject c = hasil.getJSONObject(i);
kode_d = c.getString("kd");
nama_d = c.getString("nm");
harga_d = c.getString("hrg");
des_d = c.getString("deskripsi");
}
}
else {
Log.e("erro", "tidak bisa ambil data 0");
}
}
catch (Exception e) {
// TODO: handle exception
Log.e("erro", "tidak bisa ambil data 1");
}
return kode_d;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
kode.setText(kode_d);
nama.setText(nama_d);
harga.setText(harga_d);
deskripsi.setText(des_d);
}
}
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}
catch (Exception e) {
Log.e("Buffer Error", "Error converting result " +e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
}
catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " +e.toString());
}
// return JSON String
return jObj;
}
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}
catch (Exception e) {
Log.e("Buffer Error", "Error converting result " +e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
}
catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " +e.toString());
}
// return JSON String
return jObj;
}
}
It is because you don't return any value from the doInBackground() (always return null) and you are not using the 'string' in the onPostExecute(String result) formal parameter. Garbage-In-Garbage-Out
your doInBackground() returns just a string return kode_d; and then in your onPostExecute(String result) (which expects a String) you use the kode_d which is null.
If you want all of those values to be returned create an ArrayList(), return it at the end doInBackground() and get it in onPostExecute(ArrayList result) with an iteration and pass it to you textviews.
Even better create an object and add the values to each field. Your fields are the kode_d, nama_d, harga_d, des_d
this is what the onPostExecute does
/**
* <p>Runs on the UI thread after {#link #doInBackground}. The
* specified result is the value returned by {#link #doInBackground}.
* To better support testing frameworks, it is recommended that this be
* written to tolerate direct execution as part of the execute() call.
* The default version does nothing.</p>
*
* <p>This method won't be invoked if the task was cancelled.</p>
*
* #param result The result of the operation computed by {#link #doInBackground}.
*
* #see #onPreExecute
* #see #doInBackground
* #see #onCancelled(Object)
*/
hey friends i am developing android login registration system using php and mysql on localhost.. i done coding part but my code content some run-time error when i run my app then it at register screen shows "Invalid username or password or email" that means i am getting jsonresult 0 from php means my data like(name,email,pass) is not passing to php....below is my code
for Register.java
public class Register extends Activity {
TextView tvlogin;
EditText etuname,etemail,etpass,etmobno;
Button userreg;
String name,email,pass;
// private ProgressDialog pDialog;
int flag=0;
private static String url = "http://10.0.2.2/examtime/register.php";
// private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
//StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
//.detectDiskReads().detectDiskWrites().detectNetwork()
//.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
etuname=(EditText)findViewById(R.id.et_name);
etemail=(EditText)findViewById(R.id.et_email);
etpass=(EditText)findViewById(R.id.et_password);
userreg=(Button)findViewById(R.id.button1);
// etmobno=(EditText)findViewById(R.id.editText1);
tvlogin=(TextView)findViewById(R.id.tv_login);
userreg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
userReg(v);
}
});
}
public void userReg(View v)
{
name=etuname.getText().toString();
email=etemail.getText().toString();
// mobno=etmobno.getText().toString();
pass=etpass.getText().toString();
if(name.equals("") || pass.equals("") || email.equals("")){
Toast.makeText(Register.this, "Username or password or email must be filled", Toast.LENGTH_LONG).show();
return;
}
if(name.length() <= 1 || pass.length() <= 1){
Toast.makeText(Register.this, "Username or password length must be greater than one", Toast.LENGTH_LONG).show();
return;
}
// request authentication with remote server4
AsyncDataClass asyncRequestObject = new AsyncDataClass();
asyncRequestObject.execute(url, name, pass, email);
}
private class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResult = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name", params[1]));
nameValuePairs.add(new BasicNameValuePair("pass", params[2]));
nameValuePairs.add(new BasicNameValuePair("email", params[3]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
System.out.println("Returned Json object " + jsonResult.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Resulted Value: " + result);
if(result.equals("") || result == null){
Toast.makeText(Register.this, "Server connection failed", Toast.LENGTH_LONG).show();
return;
}
int jsonResult = returnParsedJsonObject(result);
if(jsonResult == 0){
Toast.makeText(Register.this, "Invalid username or password or email", Toast.LENGTH_LONG).show();
return;
}
if(jsonResult == 1){
Intent intent = new Intent(Register.this, Profile.class);
intent.putExtra("USERNAME", name);
intent.putExtra("MESSAGE", "You have been successfully Registered");
startActivity(intent);
}
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
private int returnParsedJsonObject(String result){
JSONObject resultObject = null;
int returnedResult = 0;
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
//-------
}
and for login.java my mainactivity.java
public class MainActivity extends Activity {
TextView userReg;
Button userLogin;
EditText et_email,et_pass;
String login_email,login_pass;
String Logurl = "http://10.0.2.2/examtime/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userReg=(TextView)findViewById(R.id.Register);
userLogin=(Button)findViewById(R.id.Login);
et_email=(EditText)findViewById(R.id.email);
et_pass=(EditText)findViewById(R.id.pword);
userReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
userReg(v);
}
});
}
public void userReg(View v)
{
startActivity(new Intent(this,Register.class));
}
public void userLogin(View v)
{
login_email=et_email.getText().toString();
login_pass=et_pass.getText().toString();
if(login_email.equals("") || login_pass.equals("")){
Toast.makeText(MainActivity.this, "Username or password must be filled", Toast.LENGTH_LONG).show();
return;
}
if(login_email.length() <= 1 || login_pass.length() <= 1){
Toast.makeText(MainActivity.this, "Username or password length must be greater than one", Toast.LENGTH_LONG).show();
return;
}
// request authentication with remote server4
AsyncDataClass asyncRequestObject = new AsyncDataClass();
asyncRequestObject.execute(Logurl, login_email, login_pass);
startActivity(new Intent(this,Home.class));
}
private class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResult = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name", params[1]));
nameValuePairs.add(new BasicNameValuePair("pass", params[2]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Resulted Value: " + result);
if(result.equals("") || result == null){
Toast.makeText(MainActivity.this, "Server connection failed", Toast.LENGTH_LONG).show();
return;
}
int jsonResult = returnParsedJsonObject(result);
if(jsonResult == 0){
Toast.makeText(MainActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
return;
}
if(jsonResult == 1){
Intent intent = new Intent(MainActivity.this, Profile.class);
intent.putExtra("USERNAME",login_email);
intent.putExtra("MESSAGE", "You have been successfully login");
startActivity(intent);
}
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
private int returnParsedJsonObject(String result){
JSONObject resultObject = null;
int returnedResult = 0;
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
}
and my php code is
index.php
<?php
require_once 'include/user.php';
$username = "";
$password = "";
$email = "";
if(isset($_POST['name'])){
$username = $_POST['name'];
}
if(isset($_POST['pass'])){
$password = $_POST['pass'];
}
if(isset($_POST['email'])){
$email = $_POST['email'];
}
// Instance of a User class
$userObject = new User();
// Registration of new user
if(!empty($username) && !empty($password) && !empty($email)){
$hashed_password = md5($password);
$json_registration = $userObject->createNewRegisterUser($username, $hashed_password, $email);
echo json_encode($json_registration);
}
// User Login
if(!empty($username) && !empty($password) && empty($email)){
$hashed_password = md5($password);
$json_array = $userObject->loginUsers($username, $hashed_password);
echo json_encode($json_array);
}
?>
and my User.php
<?php
include_once 'db.php';
class User{
private $db;
private $db_table = "stud";
public function __construct(){
$this->db = new DbConnect();
}
public function isLoginExist($username, $password){
$query = "select * from " . $this->db_table . " where name = '$username' AND pass = '$password' Limit 1";
$result = mysqli_query($this->db->getDb(), $query);
if(mysqli_num_rows($result) > 0){
mysqli_close($this->db->getDb());
return true;
}
mysqli_close($this->db->getDb());
return false;
}
public function createNewRegisterUser($username, $password, $email){
$query = "insert into stud (name, pass, email) values ('$username', '$password', '$email')";
$inserted = mysqli_query($this->db->getDb(), $query);
if($inserted == 1){
$json['success'] = 1;
}else{
$json['success'] = 0;
}
mysqli_close($this->db->getDb());
return $json;
}
public function loginUsers($username, $password){
$json = array();
$canUserLogin = $this->isLoginExist($username, $password);
if($canUserLogin){
$json['success'] = 1;
}else{
$json['success'] = 0;
}
return $json;
}
}
?>
i know i am missing something i try to explain it sorry for bad English and i am also new to android and also new in stack overflow
tbh it was too much code for me to read through all of this, but I think I know what you want.
first check if Name already exists:
<?php>
$text = $_POST["text1"];
$db = #new mysqli("mysql.hostinger.de", "...", "...", "...");
if($db->connect_error){
die("<pre>".$db->connect_error."</pre>");
}
$num = $sql->num_rows;
$sql = $db->query("SELECT name FROM Rangliste");
$num = $sql->num_rows;
if($num > 0){
while($row = $sql->fetch_object()){
if($row->name == $text){
echo("Name already exists!");
}else{
echo("Name accepted!");
}
}
}
and so on... connect it with your java
Here i am fetch sms from phone and upload 10 sms on server all code working fine but instead of 10 sms upload to server only Specific one sms uploaded 10 time to server, pls tell me what i am missing in my code?
here is my message_class.Java code.
public class message_class extends Activity{
int j = 0;
Button btninbox;
ListView lstView;
SimpleCursorAdapter adapter;
ArrayList<Message_Item> msg_list;
String Str_Msg, Str_Phone,dated;
Msg_adapter msg_adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.msginbox_layout);
msg_list = new ArrayList<Message_Item>();
btninbox = (Button) findViewById(R.id.btn_inbox);
btninbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(message_class.this, Msg_Recive.class);
startActivity(intent);
}
});
lstView = (ListView) findViewById(R.id.lv_msg);
fetchInbox();
final int arraysize = msg_list.size();
for (int j=0; j<10;j++){
Str_Msg = msg_list.get(j).getStrMsg().toString();
Str_Phone = msg_list.get(j).getStrNumber().toString();
Toast.makeText(message_class.this, Str_Phone+" "+Str_Msg, Toast.LENGTH_LONG).show();
new HttpAsyncTask()
.execute("http://demo.glowsosl.com/synchs_dsda_app/insert_details_msg.php");
msg_adapter.notifyDataSetChanged();
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
Contacts person = new Contacts();
person.setPhone(Str_Phone);
person.setName(Str_Msg);
return POST(urls[0], person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result + "Data Sent!",
Toast.LENGTH_LONG).show();
}
}
private static String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public static String POST(String url, Contacts person) {
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("contact_no", person.getPhone());
jsonObject.accumulate("sim_num", "Unknown");
jsonObject.accumulate("msg", person.getName());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the
// content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result + "," + person.getName() + ","
+ person.getPhone();
}
ArrayList<String> jsonStringToArray(String jsonString) throws JSONException {
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
stringArray.add(jsonArray.getString(i));
}
return stringArray;
}
public void fetchInbox() {
// ArrayList sms = new ArrayList();
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(uriSms,
new String[] { "_id", "address", "date", "body" }, null, null,
null);
//for (int i =0; i<((JSONArray) cursor).length();i++){
//Toast.makeText(getApplicationContext(), "work", Toast.LENGTH_SHORT).show();
//}
cursor.moveToFirst();
while (cursor.moveToNext()) {
String address = cursor.getString(1);
String date = cursor.getString(2);
String body = cursor.getString(3);
// Toast.makeText(getApplicationContext(), cursor.getString(2), Toast.LENGTH_SHORT).show();
msg_list.add(new Message_Item(address, body,date));
}
msg_adapter = new Msg_adapter(msg_list, message_class.this);
lstView.setAdapter(msg_adapter);
}
Instead of applying for loop out side async task use it in doInBackground method.
Your doInBackground method will look like follows.
#Override
protected String doInBackground(String... urls) {
String result="";
for(int i = 0; i < msg_list.size(); i++){
Str_Msg = msg_list.get(i).getStrMsg().toString();
Str_Phone = msg_list.get(i).getStrNumber().toString();
Contacts person = new Contacts();
person.setPhone(Str_Phone);
person.setName(Str_Msg);
result= result + POST(urls[0], person);
}
return result;
}
And call this async task only once.
Enjoy!!
I'm trying to program an app to send a String to a service. A friend of mine has a service to receive the data.
Logcat shows this error: "org.json.JSONException: Value FIRST of type java.lang.String cannot be converted to JSONObject"
Here is my code:
Main Activity
public class MainActivity extends Activity {
private String URL = "String with my friend's url";
private Button btnAddValue;
String num = "1";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup answer = (RadioGroup) findViewById(R.id.answer);
answer.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId) {
case R.id.answerA:
num = "1";
break;
case R.id.answerB:
num = "2";
break;
case R.id.answerC:
num = "3";
break;
}
}
});
btnAddValue = (Button) findViewById(R.id.submit);
btnAddValue.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
new AddNewValue().execute(num);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
private class AddNewValue extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... arg) {
// TODO Auto-generated method stub
String number = arg[0];
// Preparing post params
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("number", number));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(URL,
ServiceHandler.POST, params);
Log.d("Create Request: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
boolean error = jsonObj.getBoolean("error");
// checking for error node in json
if (!error) {
// new category created successfully
Log.e("Value added successfully ",
"> " + jsonObj.getString("message"));
} else {
Log.e("Add Error: ",
"> " + jsonObj.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "JSON data error!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
Service Handler
public class ServiceHandler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error: " + e.toString());
}
return response;
}
}
I read questions to other people with the same problem. The solution seemed to be to add a "{" at the beginning of the json String and a "}" at the end, but it didn't work to me. I tried changing this:
String json = serviceClient.makeServiceCall(URL_NEW_PREDICTION,
ServiceHandler.POST, params);
to this:
String json = "{" + serviceClient.makeServiceCall(URL_NEW_PREDICTION,
ServiceHandler.POST, params) + "}";
but the I got this error:
"org.json.JSONException: Expected ':' after FIRST at character 9 of {FIRST DATA New record created successfully}"
You're receiving back a string that is not able to be parsed to JSON. You can't just make something JSON by adding braces, it needs to adhere to proper JSON formatting. This site shows some good examples of what that means.
Specifically, the parser is telling you that having a space after FIRST isn't okay without having quotes around it...but just adding that won't fix the issue, the problem is more deep than that.
I have a php script that returns this json array.
{"PID":"1","PName":"Guitar","Brand":"Fender","Price":"110","Cat#":"1","Typ#":"1"}
I am making a simple app that places these results into several text views. only one product is returned each time as above.
when I run the app I get this Error: org.json.JSONException: Value
{"Typ#":"1","Brand":"test","Cat#":"1","PName":"Test","PID":"2","Price":"120"}
of type org.json.JSONObject cannot be converted to JSONArray.
Here is my code. Is there something wrong with the json result or the code?
public class MainActivity extends ActionBarActivity {
TextView tvname;
TextView tvbrand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvname = (TextView) findViewById(R.id.tvName);
tvbrand = (TextView) findViewById(R.id.tvBrand);
Button btnPost = (Button) findViewById(R.id.btnPost);
btnPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new getPro().execute();
}
});
}//end of on create
private class getPro extends AsyncTask<String,String,Void>{
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
getPro.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... strings) {
String url_select = "http://10.0.2.2/OnetoOne/getProduct.php";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("pid", "2"));
try {
// Set up HTTP post
// HttpClient is more then less deprecated. Need to change to URLConnection
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// Read content & Log
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
//parse JSON data
try {
JSONArray jArray = new JSONArray(result);
//JSONObject jObject = jArray.getJSONObject(0);
String anem = jArray.getJSONObject(0).getString("PName");
//String getname = jObject.getString("PName");
//String getbrand = jObject.getString("Brand");
tvname.setText(anem);
//tvbrand.setText(getbrand);
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
}
}
}//end of async
}//end of class
Any help would be greatly appreciated.
That's not an array it's an object
JSONObject jObject = new JSONObject(result);
String anem = jObject.getString("PName");
tvname.setText(anem);
{"Typ#":"1","Brand":"test","Cat#":"1","PName":"Test","PID":"2","Price":"120"} of type org.json.JSONObject cannot be converted to JSONArray.
You are trying to convert a JSONObject into a JSONArray, this is your error.
Use :
JSONOjbect jso = new JSONObject(result);
A JSONObject Start with { and end with }.
A JSONArray Start with [ and end with ].