Android force close after sending data to server via php - php

I have a program to read data from SQL Server using php file. When I running my program and click the button search my program always close. In my logcat no one error message
My code android like this
Toolbar toolbar;
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputign;
TextView registerErrorMsg;
Button searchign;
// url to create news
private static String url_create_idgm = "http://192.168.1.111/add/csp_ign.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cps_ign);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
TypedValue typedValueColorPrimaryDark = new TypedValue();
CSPviaIGN.this.getTheme().resolveAttribute(R.attr.colorPrimary, typedValueColorPrimaryDark, true);
final int colorPrimaryDark = typedValueColorPrimaryDark.data;
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(colorPrimaryDark);
}
// Edit Text
inputign = (EditText) findViewById(R.id.inputign);
registerErrorMsg = (TextView) findViewById(R.id.error);
// Create button
searchign = (Button) findViewById(R.id.btnign);
// button click event
searchign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new NetCheck().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class NetCheck extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CSPviaIGN.this);
pDialog.setMessage("Creating ID Game Master..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = inputign.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("ign", name));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject obj = jsonParser.makeHttpRequest(url_create_idgm,
"POST", params);
// check log cat fro response
Log.d("Create Response", obj.toString());
// check for success tag
try {
int success = obj.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
//Toast.makeText(CreateIDGM.this, "Success Create ID Game Master ", Toast.LENGTH_SHORT).show();
//JSONObject obj = jParser.makeHttpRequest(url_create_idgm, "GET", params);
JSONArray account = obj.getJSONArray("detail");
JSONObject firstOnlineObject = account.getJSONObject(0);
String accountign = firstOnlineObject.getString("Account");
JSONArray ign = obj.getJSONArray("detail");
JSONObject secondOnlineObject = ign.getJSONObject(0);
String Name = secondOnlineObject.getString("Name");
JSONArray race = obj.getJSONArray("detail");
JSONObject thirdOnlineObject = race.getJSONObject(0);
String bangsa = thirdOnlineObject.getString("Race");
JSONArray classign = obj.getJSONArray("detail");
JSONObject forthOnlineObject = classign.getJSONObject(0);
String job = forthOnlineObject.getString("Class");
JSONArray map = obj.getJSONArray("detail");
JSONObject fifthOnlineObject = map.getJSONObject(0);
String location = fifthOnlineObject.getString("Map");
JSONArray level = obj.getJSONArray("detail");
JSONObject sixthOnlineObject = level.getJSONObject(0);
String Lv = sixthOnlineObject.getString("Level");
JSONArray dalant = obj.getJSONArray("detail");
JSONObject seventhOnlineObject = dalant.getJSONObject(0);
String money = seventhOnlineObject.getString("Dalant");
JSONArray gold = obj.getJSONArray("detail");
JSONObject eighthOnlineObject = gold.getJSONObject(0);
String emas = eighthOnlineObject.getString("Gold");
JSONArray pvp = obj.getJSONArray("detail");
JSONObject ninthOnlineObject = pvp.getJSONObject(0);
String pvppoint = ninthOnlineObject.getString("PVP Point");
JSONArray cpt = obj.getJSONArray("detail");
JSONObject tenOnlineObject = cpt.getJSONObject(0);
String cptpoint = tenOnlineObject.getString("CPT Point");
JSONArray cc = obj.getJSONArray("detail");
JSONObject ccOnlineObject = cc.getJSONObject(0);
String cashcoin = ccOnlineObject.getString("Cash Coin");
JSONArray ps = obj.getJSONArray("detail");
JSONObject psOnlineObject = ps.getJSONObject(0);
String premi = psOnlineObject.getString("Premium Service");
// TextView data
TextView id = (TextView)findViewById(R.id.accountplayer);
id.setText(accountign); // id
TextView ignname = (TextView)findViewById(R.id.ignPlayer);
ignname.setText(Name); // ign
TextView raceign = (TextView)findViewById(R.id.serialplayer);
raceign.setText(bangsa); // race
TextView jobign = (TextView)findViewById(R.id.raceplayer);
jobign.setText(job); // job
TextView mapign = (TextView)findViewById(R.id.classplayer);
mapign.setText(location); // map
TextView lvign = (TextView)findViewById(R.id.lvlplayer);
lvign.setText(Lv); //level
TextView dalantign = (TextView)findViewById(R.id.dalantplayer);
dalantign.setText(money); // dalant
TextView goldign = (TextView)findViewById(R.id.goldplayer);
goldign.setText(emas); // gold
TextView pvpign = (TextView)findViewById(R.id.pvpplayer);
pvpign.setText(pvppoint); // pvp
TextView cptign = (TextView)findViewById(R.id.cptplayer);
cptign.setText(cptpoint); //cpt
TextView cashign = (TextView)findViewById(R.id.cc);
cashign.setText(cashcoin); // cash
TextView premiign = (TextView)findViewById(R.id.premi);
premiign.setText(premi); // premi
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
Intent i = new Intent(getApplicationContext(), CSPviaIGN.class);
//i.putExtra("key",inputign.getText().toString());
startActivity(i);
}
}
My code php like this
<?php
//$_POST['ign'] = "CaptainJugger";
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['ign'])) {
$ign = $_POST['ign'];
/* All database connection variables */
define('DB_USER', ""); // db user
define('DB_PASSWORD', ""); // db password
define('DB_DATABASE', "RF_World"); // database name
define('DB_SERVER', "127.0.0.1"); // db server
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/** Function to connect with database **/
function connect() {
// Connecting to mssql database
$con = mssql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mssql_error());
// Selecing database
$db = mssql_select_db(DB_DATABASE) or die(mssql_error()) or die(mssql_error());
// returing connection cursor
return $con;
}
/** Function to close db connection **/
function close() {
// closing db connection
mssql_close();
}
}
// connecting to db
$db = new DB_CONNECT();
// mssql inserting a new row
$result = mssql_query("SELECT Account, Name, Race, Class, Map, Lv, Dalant, Gold, c.PvpPoint, PvpCash, Cash, d.Status FROM tbl_base a
INNER JOIN tbl_general b ON b.Serial = a.Serial
INNER JOIN tbl_pvporderview c ON c.serial = a.Serial
INNER JOIN [BILLING].[dbo].tbl_UserStatus d ON d.id = a.Account
WHERE Name= '$ign';");
// status premium service
if ($res['Status'] == 1){
$status = 'Deactive';
} else {
$status = 'Active';
}
// status race
if ($res['Race'] == 0){
$race = 'Bellato';
} elseif ($res['Race'] == 1){
$race = 'Bellato';
} elseif ($res['Race'] == 2){
$race = 'Cora';
} elseif ($res['Race'] == 3){
$race = 'Cora';
} else {
$race = 'Accretia';
}
// check if row inserted or not
if (mssql_num_rows($result) > 0) {
// looping through all results
// products node
$response["detail"] = array();
while ($row = mssql_fetch_array($result)) {
// temp user array
$product = array();
$product["Account"] = $row["Account"];
$product["Name"] = $row["Name"];
$product["Race"] = $row["Race"];
$product["Class"] = $row["Class"];
$product["Map"] = $row["Map"];
$product["Level"] = $row["Lv"];
$product["Dalant"] = $row["Dalant"];
$product["Gold"] = $row["Gold"];
$product["PVP Point"] = $row["PvpCash"];
$product["CPT Point"] = $row["PvpPoint"];
$product["Cash Coin"] = $row["Cash"];
$product["Premium Service"] = $row["Status"];
// push single product into final response array
array_push($response["detail"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No News DZoneConnect Now";
}
}
else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
My code php when I run in browser like this http://prntscr.com/bfjl5a and http://prntscr.com/bfjlf3
Anyone can help me to solve my problem?

Related

Passing data from android studio to php

I amm new in android. I want to get value of my id using json to my php server
so I can get all data i want from my database.
This is query I want to do
$query1=mysqli_query($con,"SELECT * FROM jadwal_matakuliah WHERE nim_mhs ='$id'");
my php code
<?php
include "koneksi.php";
$username = $_POST["id"];
$query1=mysqli_query($con,"SELECT * FROM jadwal_matakuliah WHERE nim_mhs ='$id'");
if($query)
{
while($row=mysqli_fetch_array($query))
{
$flag[]=$row;
}
print(json_encode($flag));
}
mysqli_close($con);
?>
my android code
String id, username;
SharedPreferences sharedpreferences;
public static final String TAG_ID = "id";
public static final String TAG_USERNAME = "username";
String urladdress="http://10.0.2.2/multi/menu_mhs.php";
String[] name;
String[] jam;
String[] email;
String[] imagepath;
ListView listView;
BufferedInputStream is;
String line=null;
String result=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
listView=(ListView)findViewById(R.id.lview);
StrictMode.setThreadPolicy((new StrictMode.ThreadPolicy.Builder().permitNetwork().build()));
collectData();
CustomListView customListView=new CustomListView(this,name,email,imagepath,jam);
listView.setAdapter(customListView);
// getSupportActionBar().setTitle("MHS");
txt_id = (TextView) findViewById(R.id.txt_id);
txt_username = (TextView) findViewById(R.id.txt_username);
btn_logout = (Button) findViewById(R.id.btn_logout);
sharedpreferences = getSharedPreferences(Login.my_shared_preferences, Context.MODE_PRIVATE);
id = getIntent().getStringExtra(TAG_ID);
username = getIntent().getStringExtra(TAG_USERNAME);
txt_id.setText("" + id);
txt_username.setText("( " + username +" )");
}
private void collectData() {
//Connection
try {
URL url = new URL(urladdress);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
is = new BufferedInputStream(con.getInputStream());
} catch (Exception ex) {
ex.printStackTrace();
}
//content
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
}
//JSON
try {
JSONArray ja = new JSONArray(result);
JSONObject jo = null;
name = new String[ja.length()];
jam = new String[ja.length()];
email = new String[ja.length()];
imagepath = new String[ja.length()];
for (int i = 0; i <= ja.length(); i++) {
jo = ja.getJSONObject(i);
name[i] = jo.getString("nama_matakuliah");
email[i] = jo.getString("dosen");
imagepath[i] = jo.getString("photo");
jam[i] = jo.getString("jadwal");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
You can send the id as a query parameter with your URL,
ie if your URL is example.com/hello then
you can call it as example.com/hello?id=your_id

Delete from Mysql (android)

so yesterday it was working fine , all i did today was change the url cause my ip address changes , i dont know what's wrong with it , it says * deleted perfectly* but it actually doesn't delete a thing
here's my php script
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "restaurant";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//$_POST["sIDCOMMANDES"]=6;
$commandesID = $_POST["sIDCOMMANDES"];
$strSQL = "DELETE FROM commandes WHERE 1 AND ID_COMMANDES = '".$commandesID."' ";
$result = $conn->query($strSQL);
if(!$result)
{
$ar["StatusID"] = "0";
$ar["Error"] = "Cannot delete data!";
}
else
{
$ar["StatusID"] = "1";
$ar["Error"] = "";
}
print(json_encode($ar));
$conn->close();
?>
I ve tested it and it s working fine , now here s my code for deleting a row from my listview
public class ImageAdapter extends BaseAdapter
{
private Context context;
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.get_all_comm_list_view, null);
}
ImageButton cmdDelete = (ImageButton) convertView.findViewById(R.id.btnDelete);
cmdDelete.setBackgroundColor(Color.TRANSPARENT);
final AlertDialog.Builder adb1 = new AlertDialog.Builder(Comm.this);
final AlertDialog.Builder adb2 = new AlertDialog.Builder(Comm.this);
cmdDelete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
adb1.setTitle("Delete?");
adb1.setMessage("Are you sure delete [" + MyArrList.get(position).get("NOM_PLAT") +"]");
adb1.setNegativeButton("Cancel", null);
adb1.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String url = "http://192.168.1.7/deleteData.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sIDCOMMANDES", MyArrList.get(position).get("ID_COMMANDES")));
String resultServer = getJSONUrll(url, params);
String strStatusID = "0";
String strError = "Unknown Status";
try {
JSONObject c = new JSONObject(resultServer);
strStatusID = c.getString("StatusID");
strError = c.getString("Error");
} catch (JSONException e) {
e.printStackTrace();
}
if(strStatusID.equals("0"))
{
adb2.setTitle("Error! ");
adb2.setPositiveButton("Close", null);
adb2.setMessage(strError);
adb2.show();
}
else
{
Toast.makeText(Comm.this, "Delete data successfully.", Toast.LENGTH_SHORT).show();
ShowData(); // reload data again
}
}});
adb1.show();
}
});

How to make random data without repetition on ClikListener

I want to show a random question. On my layout there's an imageView and a button. An imageView will replace with a question which located in my server, and a button for the next question. I made randomize question in my PHP. But every time I clicked next Button, some question showing again, it's because every time I clicked next Button, it will execute the randomize PHP. My question is, how to make next button without execute randomize PHP?
It's my PHP code:
<?php
$host="localhost";
$username="root";
$password="";
mysql_connect($host,$username,$password);
$database_name="db_ipa";
mysql_select_db($database_name);
$arr = array();
$q = mysql_query("select * from biologi order by rand() limit 10");
while ($row = mysql_fetch_assoc($q)) {
$temp = array(
"no" => $row['no'],
"soal"=>$row['soal'],
);
array_push($arr, $temp);
}
$data = json_encode($arr);
$data = str_replace("\\", "", $data);
echo "$data";
?>
It's my onClick method:
public void next(View v){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
JSONParser jParser = new JSONParser();
String url ="http://192.168.137.1/server/soal.php";
String json = jParser.makeHttpRequestPOSTNew(url);
Log.d("json", json);
ImageView img1 = (ImageView) findViewById(R.id.imageView1);
try {
JSONArray jArray = new JSONArray(json);
StringBuffer str[] = new StringBuffer[jArray.length()];
for(int i=0;i<=10;i++){
if(i==10){
Intent intent = new Intent(getApplicationContext(), Nilai.class);
startActivity(intent);
}
str[i] = new StringBuffer();
JSONObject soal = jArray.getJSONObject(i);
String sSoal = soal.getString("soal");
img1.setImageBitmap(BitmapFactory.decodeStream((InputStream) new URL("http://192.168.137.1/server/" + sSoal).getContent()));
}
} catch (Exception e) {
// TODO: handle exception
}
}

Android : DB table won't update

In my app I have an EditText where the user can add his personal info. When he is done writing, he clicks a button and the corresponding DB column is supposed to be updated, but is not.
Here is my php script :
<?php
$con = mysqli_connect('127.0.0.1','root','lokijuhy1');
mysqli_select_db($con,'twentythree');
$response = array();
if(isset($_POST['about_me']) && isset($_POST['name']) && isset($_POST['uid'])){
$about_me = $_POST['about_me'];
$name = $_POST['name'];
$uid = $_POST['uid'];
$query = "UPDATE profile SET about_me = $about_me WHERE unique_id = $uid";
$result = mysqli_query($con,$query);
if ($result){
$response["success"] = 1;
$response["message"] = "Success";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Table was not Updated";
echo json_encode($response);
}
}else {
$response["success"] = 0;
$response["message"] = "Something is missing!";
echo json_encode($response);
}
?>
And here is my Java code :
class updateProfile extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name",name));
params.add(new BasicNameValuePair("uid",uid));
params.add(new BasicNameValuePair("about_me", about_me));
JSONParser jsonParser = new JSONParser();
JSONObject json = jsonParser.makeHttpRequest(Config.URL_profileUpdate,
"POST", params);
try {
// Checking for SUCCESS TAG
int success = json.getInt("success");
String message = json.optString("message");
if (success == 1) {
System.out.println(message);
}
}catch (JSONException e) {
e.printStackTrace();
}
return null;
protected void onPostExecute(String file_url) {
}
Do you guys have any idea why this happens?
Note : I just noticed that I get a positive JSON response, but the response message is null.

select values with specific id from php to android

my codes is fine, not returning any errors but the values being retrieved are the same as the previous field..for example, if i set table3 to 'HELLO' then table4 is also 'HELLO' which is kinda wrong,i wanted separate values..here is my code...
my SigninActivity:
public class SigninActivity extends AsyncTask<String,Void,String>{
private TextView statusField,roleField, sampleField;
private Context context;
private int byGetOrPost = 0;
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,TextView roleField,TextView sampleField,int flag) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
this.sampleField = sampleField;
byGetOrPost = flag;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://XXX.XXX.X.X/XXX/ins.php?username="
+username+"&password="+password;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://XXX.XXX.X.X/XXX/sel.php";
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
#Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
this.sampleField.setText(result);
}
}
my select.php file (sel.php):
<?php
$con=mysqli_connect("localhost","root","","db_name");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"SELECT role,sample FROM table1 WHERE
username='$username' and password='$password'");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo $data;
}
mysqli_close($con);
?>
This is where your problem is:
#Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
this.sampleField.setText(result);
}
If you want different values for sampleField and roleField, you should set different values.
Update
I see where your other problem is. In the un-updated PHP source, you are selecting both role and sample from the database table, but you are outputting only role because $data equals $row[0]. If you want sample as well, you would need to retrieve $row[1] as well.
Or you could also use $row["role"] and $row["sample"] to get the values returned from the database table.
<?php
$con=mysqli_connect("localhost","root","","db_name");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"SELECT role,sample FROM table1 WHERE
username='$username' and password='$password'");
$row = mysqli_fetch_array($result);
if($row){
// returns a json object in the form
// {"role":"<role-from-database>","sample":"<sample-from-database>"}
$output = array("role" => $row["role"] ,"sample" => $row["sample"]);
echo json_encode($output);
}
mysqli_close($con);
?>
With the updated PHP source, you should process the JSON object in your SigninActivity.
Update 2
#Override
protected void onPostExecute(String result){
String role = "", sample = "";
// read the json object with JsonReader
JsonReader reader = new JsonReader(new StringReader(result));
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("role")) {
role = reader.nextString();
} else if (name.equals("sample")) {
sample = reader.nextString();
} else {
reader.skipValue();
}
}
reader.endObject();
// set the text here
}
Let me know if this helps.

Categories