Android - Exception using main thread and posting data to PHP - java

When I run my android app and activate a click event that tries to transfer data from a table row to post it to a PHP file, the main thread forces the app to shut-down regardless of using another thread in the background to establish the network connection (using AsyncTask). Below I have provided my files:
MainActivity.java
package com.example.stevenkennedy.categorizer;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
public class MainActivity extends AppCompatActivity {
// Local Variables
private Boolean snapBool = false;
private Boolean snapBool2 = false;
private Boolean snapBool3 = false;
private Boolean snapBool4 = false;
private Boolean snapBool5 = false;
// Add ImageView objects for camera
private ImageView snap;
private ImageView snap2;
private ImageView snap3;
private ImageView snap4;
private ImageView snap5;
private static final int CAMERA_REQUEST = 1888;
// Add Button for click event for server communication
private Button sendBtn;
// Row 1
private EditText idRow1;
private EditText nameRow1;
private Spinner categoryRow1;
private EditText commentRow1;
private EditText priceRow1;
private ImageView galleryRow1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Row 1
idRow1 = (EditText) findViewById(R.id.idBox);
nameRow1 = (EditText) findViewById(R.id.nameBox);
categoryRow1 = (Spinner) findViewById(R.id.cateBox);
commentRow1 = (EditText) findViewById(R.id.commBox);
priceRow1 = (EditText) findViewById(R.id.priceBox);
galleryRow1 = (ImageView) findViewById(R.id.gallBox);
// listeners for camera event
snap = (ImageView) findViewById(R.id.gallBox);
snap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
// flag local boolean
snapBool = true;
}
});
snap2 = (ImageView) findViewById(R.id.gallBox2);
snap2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
// flag local boolean
snapBool2 = true;
}
});
snap3 = (ImageView) findViewById(R.id.gallBox3);
snap3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
// flag local boolean
snapBool3 = true;
}
});
snap4 = (ImageView) findViewById(R.id.gallBox4);
snap4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
// flag local boolean
snapBool4 = true;
}
});
snap5 = (ImageView) findViewById(R.id.gallBox5);
snap5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
// flag local boolean
snapBool5 = true;
}
});
// confirm button to send data to server
sendBtn = (Button) findViewById(R.id.send);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// create AsyncTask to get user entered cell data
new MyTask().execute();
}
});
} // ******** ON CREATE END ************
/*
* Method that activates the camera and gets a thumbnail of the photo for the
* table cell
*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
if (snapBool == true) {
snap.setImageBitmap(photo);
} else if (snapBool2 == true) {
snap2.setImageBitmap(photo);
} else if (snapBool3 == true) {
snap3.setImageBitmap(photo);
} else if (snapBool4 == true) {
snap4.setImageBitmap(photo);
} else if(snapBool5 == true) {
snap5.setImageBitmap(photo);
}
// set boolean flags back to false
snapBool = false;
snapBool2 = false;
snapBool3 = false;
snapBool4 = false;
snapBool5 = false;
}
}
/*
* Method to get cell data of Row 1 and send it to a sql server using
* post data with php
*/
public void getCells() {
// get the data in boxes
String str1 = idRow1.getText().toString();
String str2 = nameRow1.getText().toString();
String str3 = categoryRow1.getSelectedItem().toString();
String str4 = commentRow1.getText().toString();
String str5 = priceRow1.getText().toString();
//galleryRow1.get
// create sql object
MySQLConnect sql = new MySQLConnect(str1, str2, str3, str4, str5, "png23.png");
sql.sendTo();
}
/**
* AsyncTask Class
*/
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
getCells();
return null;
}
protected void onPostExecute(String result) {}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
} // ************** CLASS END **************
MySQLConnect.java
package com.example.stevenkennedy.categorizer;
import android.media.Image;
import android.os.AsyncTask;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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;
/**
* Created by Steven Kennedy on 27/10/2015.
*/
public class MySQLConnect {
// Class Variables
private String id;
private String name;
private String cate;
private String comm;
private String price;
private String gall;
// constructor
public MySQLConnect(String id, String name, String cate, String comm, String price, String gall){
this.id = id;
this.name = name;
this.cate = cate;
this.comm = comm;
this.price = price;
this.gall = gall;
}
// getters and setters
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCate() {
return cate;
}
public void setCate(String cate) {
this.cate = cate;
}
public String getComm() {
return comm;
}
public void setComm(String comm) {
this.comm = comm;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getGall() {
return gall;
}
public void setGall(String gall) {
this.gall = gall;
}
public void sendTo() {
// HTTP client
HttpClient client = new DefaultHttpClient();
// use php to post data to
HttpPost post = new HttpPost("http://myPHPfile.com/myFile.php");
try {
// add to arraylist
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
// add values
nameValuePairs.add(new BasicNameValuePair("id", this.getId() ));
nameValuePairs.add(new BasicNameValuePair("name", this.getName()));
nameValuePairs.add(new BasicNameValuePair("category", this.getCate()));
nameValuePairs.add(new BasicNameValuePair("comment", this.getComm()));
nameValuePairs.add(new BasicNameValuePair("price", this.getPrice()));
//nameValuePairs.add(new BasicNameValuePair("gallery", this.getGall()));
// send to server - POST
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//HttpResponse response = client.execute(post);
client.execute(post);
} catch (ClientProtocolException ed) {
// TODO Auto-generated catch block
ed.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} // ********* END ***********
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Header Table -->
<TableLayout
android:id="#+id/topTable"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="left|top"
android:background="#B3EAFF">
<TableRow android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:padding="10dip">
<TextView
android:id="#+id/idTitle"
android:text="id"
android:gravity="right"
android:paddingRight="70dp"/>
<TextView
android:text="Name"
android:paddingRight="75dp"/>
<TextView
android:text="Category"
android:paddingRight="55dp" />
<TextView
android:text="Comment"
android:paddingRight="45dp" />
<TextView
android:text="Price"
android:paddingRight="30dp" />
<TextView
android:text="Gallery" />
</TableRow>
<!-- drawn line -->
<View
android:layout_height="2dip"
android:background="#FF909090" />
</TableLayout>
<!-- Scroll Layout -->
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView"
android:layout_below="#+id/topTable"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:scrollbars="vertical">
<RelativeLayout
android:layout_width="fill_parent"
android:orientation="vertical"
android:id="#+id/linearLayout1"
android:layout_height="fill_parent"
android:layout_alignTop="#+id/scrollView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<!-- Row 1 -->
<EditText
android:layout_width="70dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:id="#+id/idBox" />
<EditText
android:layout_width="110dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:id="#+id/nameBox"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/idBox"
android:layout_toEndOf="#+id/idBox" />
<Spinner
android:layout_width="110dip"
android:layout_height="45dip"
android:entries="#array/cate_array"
android:prompt="#string/cate_spin"
android:background="#drawable/border_style"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/nameBox"
android:layout_toEndOf="#+id/nameBox"
android:id="#+id/cateBox" />
<EditText
android:layout_width="120dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/cateBox"
android:layout_toEndOf="#+id/cateBox"
android:id="#+id/commBox" />
<EditText
android:layout_width="60dip"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:digits="0123456789."
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/commBox"
android:layout_toEndOf="#+id/commBox"
android:id="#+id/priceBox" />
<!--<EditText
android:layout_width="90dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:onClick="true"
android:text=" [ O ]"
android:editable="false"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/priceBox"
android:layout_toEndOf="#+id/priceBox"
android:id="#+id/gallBox" />-->
<ImageView
android:layout_width="90dip"
android:layout_height="45dip"
android:background="#drawable/border_style"
android:onClick="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/priceBox"
android:layout_toEndOf="#+id/priceBox"
android:id="#+id/gallBox"/>
<!-- Row 2 -->
<EditText
android:layout_width="70dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_below="#+id/idBox"
android:id="#+id/idBox2" />
<EditText
android:layout_width="110dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:id="#+id/nameBox2"
android:layout_below="#+id/nameBox"
android:layout_toRightOf="#+id/idBox2" />
<Spinner
android:layout_width="110dip"
android:layout_height="45dip"
android:entries="#array/cate_array"
android:prompt="#string/cate_spin"
android:background="#drawable/border_style"
android:layout_toRightOf="#+id/nameBox2"
android:layout_below="#+id/cateBox"
android:id="#+id/cateBox2" />
<EditText
android:layout_width="120dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_toRightOf="#+id/cateBox2"
android:layout_below="#+id/commBox"
android:id="#+id/commBox2" />
<EditText
android:layout_width="60dip"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:digits="0123456789."
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_toRightOf="#+id/commBox2"
android:layout_below="#+id/priceBox"
android:id="#+id/priceBox2" />
<ImageView
android:layout_width="90dip"
android:layout_height="45dip"
android:background="#drawable/border_style"
android:onClick="true"
android:layout_toRightOf="#+id/priceBox2"
android:layout_below="#+id/gallBox"
android:id="#+id/gallBox2"/>
<!-- Row 3 -->
<EditText
android:layout_width="70dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_below="#+id/idBox2"
android:id="#+id/idBox3" />
<EditText
android:layout_width="110dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:id="#+id/nameBox3"
android:layout_below="#+id/nameBox2"
android:layout_toRightOf="#+id/idBox3" />
<Spinner
android:layout_width="110dip"
android:layout_height="45dip"
android:entries="#array/cate_array"
android:prompt="#string/cate_spin"
android:background="#drawable/border_style"
android:layout_toRightOf="#+id/nameBox3"
android:layout_below="#+id/cateBox2"
android:id="#+id/cateBox3" />
<EditText
android:layout_width="120dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_toRightOf="#+id/cateBox3"
android:layout_below="#+id/commBox2"
android:id="#+id/commBox3" />
<EditText
android:layout_width="60dip"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:digits="0123456789."
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_toRightOf="#+id/commBox3"
android:layout_below="#+id/priceBox2"
android:id="#+id/priceBox3" />
<ImageView
android:layout_width="90dip"
android:layout_height="45dip"
android:background="#drawable/border_style"
android:onClick="true"
android:layout_toRightOf="#+id/priceBox3"
android:layout_below="#+id/gallBox2"
android:id="#+id/gallBox3"/>
<!-- Row 4 -->
<EditText
android:layout_width="70dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_below="#+id/idBox3"
android:id="#+id/idBox4" />
<EditText
android:layout_width="110dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:id="#+id/nameBox4"
android:layout_below="#+id/nameBox3"
android:layout_toRightOf="#+id/idBox4" />
<Spinner
android:layout_width="110dip"
android:layout_height="45dip"
android:entries="#array/cate_array"
android:prompt="#string/cate_spin"
android:background="#drawable/border_style"
android:layout_toRightOf="#+id/nameBox4"
android:layout_below="#+id/cateBox3"
android:id="#+id/cateBox4" />
<EditText
android:layout_width="120dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_toRightOf="#+id/cateBox4"
android:layout_below="#+id/commBox3"
android:id="#+id/commBox4" />
<EditText
android:layout_width="60dip"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:digits="0123456789."
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_toRightOf="#+id/commBox4"
android:layout_below="#+id/priceBox3"
android:id="#+id/priceBox4" />
<ImageView
android:layout_width="90dip"
android:layout_height="45dip"
android:background="#drawable/border_style"
android:onClick="true"
android:layout_toRightOf="#+id/priceBox4"
android:layout_below="#+id/gallBox3"
android:id="#+id/gallBox4"/>
<!-- Row 5 -->
<EditText
android:layout_width="70dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_below="#+id/idBox4"
android:id="#+id/idBox5" />
<EditText
android:layout_width="110dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:id="#+id/nameBox5"
android:layout_below="#+id/nameBox4"
android:layout_toRightOf="#+id/idBox5" />
<Spinner
android:layout_width="110dip"
android:layout_height="45dip"
android:entries="#array/cate_array"
android:prompt="#string/cate_spin"
android:background="#drawable/border_style"
android:layout_toRightOf="#+id/nameBox5"
android:layout_below="#+id/cateBox4"
android:id="#+id/cateBox5" />
<EditText
android:layout_width="120dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_toRightOf="#+id/cateBox5"
android:layout_below="#+id/commBox4"
android:id="#+id/commBox5" />
<EditText
android:layout_width="60dip"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:digits="0123456789."
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_toRightOf="#+id/commBox5"
android:layout_below="#+id/priceBox4"
android:id="#+id/priceBox5" />
<ImageView
android:layout_width="90dip"
android:layout_height="45dip"
android:background="#drawable/border_style"
android:onClick="true"
android:layout_toRightOf="#+id/priceBox5"
android:layout_below="#+id/gallBox4"
android:id="#+id/gallBox5"/>
<!-- Send to server -->
<Button
android:id="#+id/send"
android:layout_width="80dp"
android:layout_height="40dp"
android:text="Send"
android:layout_below="#+id/idBox5"
android:layout_marginTop="15dp" />
</RelativeLayout>
</ScrollView>
myFile.php
<?php
$servername = "******";
$username = "*****";
$password = "*****";
$dbname = "*****";
// POST data
$idPass = $_POST['id'];
$namePass = $_POST['name'];
$catePass = $_POST['category'];
$commPass = $_POST['comment];
$pricePass = $_POST['price'];
//$gallPass = $_POST['gallery'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO viewer VALUES ('$idPass', '$namePass', '$catePass', '$commPass', '$pricePass', 'imge.png')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
If anyone knows a better way to connect to a database that doesn't require a lot of memory usage, I would gladly take that as an answer. I also know about Apache libraries being depreciated as of the latest updates, and have tried the java HttpURLConnection class to post data, but got the same issue of the main thread exception.

Probably you are getting an exception like: "Method getText() must be called from the UI thread, currently inferred thread is worker."
You cannot use the View#getText() from the background Thread in your AsyncTask.
What you need to do is to pass your Strings on your execute method changing the signature in:
private class MyTask extends AsyncTask<String, Void, Void> {

No. you just need to add :
new THread(new Runable(){on Run()}).start() to wrap up your code for request!
public void sendTo() {
new Thread(new Runnable() {
#Override
public void run() {
// HTTP client
HttpClient client = new DefaultHttpClient();
// use php to post data to
HttpPost post = new HttpPost("http://myPHPfile.com/myFile.php");
try {
// add to arraylist
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
// add values
nameValuePairs.add(new BasicNameValuePair("id", this.getId() ));
nameValuePairs.add(new BasicNameValuePair("name", this.getName()));
nameValuePairs.add(new BasicNameValuePair("category", this.getCate()));
nameValuePairs.add(new BasicNameValuePair("comment", this.getComm()));
nameValuePairs.add(new BasicNameValuePair("price", this.getPrice()));
//nameValuePairs.add(new BasicNameValuePair("gallery", this.getGall()));
// send to server - POST
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//HttpResponse response = client.execute(post);
client.execute(post);
} catch (ClientProtocolException ed) {
// TODO Auto-generated catch block
ed.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}

Related

Display text and json on activity Android Studio Java

so, I wrote a code where I get informations from a database about food.I'm asking If I can display some text with that ListView that I display.For example look here : app photo
Here are some numbers and I wanna write to all of them their description: Protein, Energy, etc.
Here is the code that I wrote :
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class LF1Activity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> resultList;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lf1);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
resultList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(LF1Activity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "https://wger.de/api/v2/ingredient/?language=2&limit=11865";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray results = jsonObj.getJSONArray("results");
// looping through All Contacts
for (int i = 0; i < results.length(); i++) {
JSONObject c = results.getJSONObject(i);
String name = c.getString("name");
String fat = c.getString("fat");
String protein = c.getString("protein");
String energy = c.getString("energy");
String carbohydrates = c.getString("carbohydrates");
String carbohydrates_sugar = c.getString("carbohydrates_sugar");
String fat_saturated = c.getString("fat_saturated");
String fibres = c.getString("fibres");
String sodium = c.getString("sodium");
// tmp hash map for single contact
HashMap<String, String> result = new HashMap<>();
// adding each child node to HashMap key => value
result.put("name",name);
result.put("fat", fat);
result.put("protein",protein);
result.put("energy",energy);
result.put("carbohydrates", carbohydrates);
result.put("carbohydrates_sugar",carbohydrates_sugar);
result.put("fat_saturated", fat_saturated);
result.put("fibres",fibres);
result.put("sodium", sodium);
// adding contact to contact list
resultList.add(result);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(LF1Activity.this, resultList,
R.layout.list_item_nutrition, new String[]{ "name","fat","energy","protein","carbohydrates","carbohydrates_sugar","fat_saturated","fibres","sodium"},
new int[]{R.id.name, R.id.fat,R.id.protein,R.id.energy,R.id.carbohydrates,R.id.carbohidrates_sugar,R.id.fat_saturated,R.id.fibres,R.id.sodium});
lv.setAdapter(adapter);
}
}
}
Here is the activity where I display them all:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".LF1Activity">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="56dp"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="0dp" />
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="411dp"
android:layout_height="wrap_content"
android:background="#000000" />
<ImageView
android:id="#+id/back_to_home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="40dp"
android:minHeight="45dp"
android:paddingTop="15dp"
android:src="#drawable/ic_back" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="16dp"
android:text="Exercise Database"
android:textAlignment="center"
android:textColor="#FFFFFFFF"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Here is the list where I store them :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:paddingTop="10dp"
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#color/colorAccent"
android:text="Name:"/>
<TextView
android:id="#+id/energy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:paddingTop="10dp"
android:text="Energy:"
/>
<TextView
android:id="#+id/protein"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Protein:"
/>
<TextView
android:id="#+id/carbohydrates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Carbohydrates:"
/>
<TextView
android:id="#+id/carbohidrates_sugar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Carbohydrates from sugar:"
/>
<TextView
android:id="#+id/fat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Fat:"
/>
<TextView
android:id="#+id/fat_saturated"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Saturated Fat:"
/>
<TextView
android:id="#+id/fibres"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Fibres:"
/>
<TextView
android:id="#+id/sodium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"
android:text="Sodium:"
/>
</LinearLayout>
try using
result.put("fat", "Fat :"+fat);

nullpointexception:error while inserting data into firebase database

i have provided a intent from the registration page to the add contacts page and in the add contacts page tried to add the details into the firebase database using two functions addusers() and addcontacts()
can somebody pls help me
this is my registration.java file
package universe.sk.syndriveapp;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class RegistrationActivity extends AppCompatActivity {
private EditText etName, etEmailsign, etPassign, etConfirmPassign, etBloodgroup, etDate;
private Button btn_register;
private TextView tvExist;
private FirebaseAuth firebaseAuth;
String name, email, password, bloodgrp, date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("SIGN UP");
setupUIViews();
firebaseAuth = FirebaseAuth.getInstance();
btn_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (validate()) {
String user_email = etEmailsign.getText().toString().trim();
String user_password = etPassign.getText().toString().trim();
//store in database:to be done after filling the contacts
firebaseAuth.createUserWithEmailAndPassword(user_email, user_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
finish();
startActivity(new Intent(RegistrationActivity.this, AddContacts.class));
//Toast.makeText(RegistrationActivity.this, "Registration Successful!", Toast.LENGTH_SHORT).show();
} else
Toast.makeText(RegistrationActivity.this, "Registration Failed!", Toast.LENGTH_SHORT).show();
}
});
//startActivity(new Intent(RegistrationActivity.this,NavigationActivity.class));
}
}
});
tvExist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
}
});
}
private void setupUIViews() {
etName = findViewById(R.id.etName);
etEmailsign = findViewById(R.id.etEmailsign);
etPassign = findViewById(R.id.etPassign);
btn_register = findViewById(R.id.btn_register);
tvExist = findViewById(R.id.tvExist);
etConfirmPassign = findViewById(R.id.etConfirmPassign);
etDate = (EditText) findViewById(R.id.etDate);
etBloodgroup = (EditText) findViewById(R.id.etBloodgroup);
}
private Boolean validate() {
Boolean result = false;
bloodgrp = etBloodgroup.getText().toString().trim();
date = etDate.getText().toString().trim();
name = etName.getText().toString();
password = etPassign.getText().toString();
email = etEmailsign.getText().toString();
String confirmpass = etConfirmPassign.getText().toString();
if (name.isEmpty() || password.isEmpty() || email.isEmpty()) {
Toast.makeText(this, "Please enter all the details!", Toast.LENGTH_SHORT).show();
} else {
if (password.equals(confirmpass))
result = true;
else
Toast.makeText(this, "Confirm password doesn't match with your password!", Toast.LENGTH_SHORT).show();
}
return result;
}
}
this is my addcontacts java file
package universe.sk.syndriveapp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class AddContacts extends AppCompatActivity {
Button registerbtn;
EditText etName,etEmailsign,etPassign,etBloodgroup,etDate;
EditText name1, num1, name2, num2, name3, num3;
String emname1,emname2,emname3;
String emnum1,emnum2,emnum3;
String name,email,password,bloodgrp,date;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addcontacts);
ActionBar actionBar = getSupportActionBar();
actionBar.setIcon(R.drawable.contacts);
actionBar.setTitle(" Add Emergency Contacts");
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
registerbtn= findViewById(R.id.registerbtn);
name1 = findViewById(R.id.name1);
num1 = findViewById(R.id.num1);
name2 = findViewById(R.id.name2);
num2 = findViewById(R.id.num2);
name3 = findViewById(R.id.name3);
num3 = findViewById(R.id.num3);
setupUIViews();
firebaseAuth = FirebaseAuth.getInstance();
registerbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int value=checkData();
if(value==1) {
emname1 = name1.getText().toString();
emnum1 = num1.getText().toString();
emname2 = name2.getText().toString();
emnum2 = num2.getText().toString();
emname3 = name3.getText().toString();
emnum3 = num3.getText().toString();
bloodgrp = etBloodgroup.getText().toString().trim();
date = etDate.getText().toString().trim();
name = etName.getText().toString();
password = etPassign.getText().toString();
email = etEmailsign.getText().toString();
adduser();
addcontacts();
/*
if (emname1.isEmpty() || emname2.isEmpty() || emname3.isEmpty()){
startActivity(new Intent(AddContacts.this, RegistrationActivity.class));
Toast.makeText(AddContacts.this, "", Toast.LENGTH_SHORT).show();
}
*/
Toast.makeText(AddContacts.this, "Registration Success!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(AddContacts.this, NavigationActivity.class));
}
}
});
}
boolean isEmpty(EditText text){
CharSequence str = text.getText().toString();
return TextUtils.isEmpty(str);
}
int checkData(){
if(isEmpty(name1) || isEmpty(name2) || isEmpty(name3) || isEmpty(num1) || isEmpty(num2) || isEmpty(num3)){
Toast.makeText(AddContacts.this,"Please fill all contact details",Toast.LENGTH_SHORT).show();
return -1;
}
else
return 1;
}
private void setupUIViews()
{
etName = findViewById(R.id.etName);
etEmailsign = findViewById(R.id.etEmailsign);
etPassign = findViewById(R.id.etPassign);
etDate =(EditText)findViewById(R.id.etDate);
etBloodgroup =(EditText) findViewById(R.id.etBloodgroup);
}
private void addcontacts(){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseusers = firebaseDatabase.getReference(firebaseAuth.getUid());
Contactdetails contactdetails;
contactdetails = new Contactdetails(emname1,emname2,emname3,emnum1,emnum2,emnum3);
databaseusers.setValue(contactdetails);
}
private void adduser(){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseusers= firebaseDatabase.getReference(firebaseAuth.getUid());
Userinfo user;
user = new Userinfo(name,email,date,bloodgrp);
databaseusers.setValue(user);
}
}
this is my userinfo java file
package universe.sk.syndriveapp;
import android.net.Uri;
import com.google.android.gms.tasks.Task;
public class Userinfo {
public String username;
public String uemail;
public String udate;
public String bloodgroup;
// public Uri imageUri;
public Userinfo(){
}
public Userinfo(String username, String uemail, String udate, String bloodgroup) {
this.username = username;
this.uemail = uemail;
this.udate = udate;
this.bloodgroup = bloodgroup;
// this.imageUri = imageUri;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUemail() {
return uemail;
}
public void setUemail(String uemail) {
this.uemail = uemail;
}
public String getUdate(){
return udate;
}
public void setUdate(String udate) {
this.udate = udate;
}
public String getBloodgroup() {
return bloodgroup;
}
public void setBloodgroup(String bloodgroup) {
this.bloodgroup = bloodgroup;
}
/* public Uri getImageUri() {
return imageUri;
}
public void setImageUri(Uri imageUri) {
this.imageUri = imageUri;
} */
}
this is my contactdetails java file
package universe.sk.syndriveapp;
public class Contactdetails {
public String cname1;
public String cname2;
public String cname3;
public String no1;
public String no2;
public String no3;
public Contactdetails(){
}
public Contactdetails(String cname1, String cname2, String cname3, String no1, String no2, String no3) {
this.cname1 = cname1;
this.cname2 = cname2;
this.cname3 = cname3;
this.no1 = no1;
this.no2 = no2;
this.no3 = no3;
}
public void setCname1(String cname1) {
this.cname1 = cname1;
}
public void setCname2(String cname2) {
this.cname2 = cname2;
}
public void setCname3(String cname3) {
this.cname3 = cname3;
}
public void setNo1(String no1) {
this.no1 = no1;
}
public void setNo2(String no2) {
this.no2 = no2;
}
public void setNo3(String no3) {
this.no3 = no3;
}
public String getCname1() {
return cname1;
}
public String getCname2() {
return cname2;
}
public String getCname3() {
return cname3;
}
public String getNo1() {
return no1;
}
public String getNo2() {
return no2;
}
public String getNo3() {
return no3;
}
}
this is my addcontacts xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/name1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:hint="#string/hint_emname1"
android:inputType="textPersonName" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/num1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hint_num1"
android:inputType="phone" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/name2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hint_emname2"
android:inputType="textPersonName" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/num2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hint_num2"
android:inputType="phone" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/name3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hint_emname3"
android:inputType="textPersonName" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/num3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hint_num3"
android:inputType="phone" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/registerbtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:layout_marginTop="25dp"
android:background="#color/colorPrimary"
android:text="#string/hint_registerbtn"
android:textColor="#FFFFFF" />
</LinearLayout>
this is my profile xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".RegistrationActivity">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/etName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:ems="10"
android:hint="#string/user_name"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.106" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/etDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="#string/date_of_birth"
android:inputType="date" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/etBloodgroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="#string/blood_group"
android:inputType="text" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/etEmailsign"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="#string/email"
android:inputType="textEmailAddress"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/etDate" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/etPassign"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="#string/password"
android:inputType="textPassword"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/etEmailsign"
app:layout_constraintVertical_bias="0.08" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#color/colorPrimary">
<EditText
android:id="#+id/etConfirmPassign"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="#string/confirm_password"
android:inputType="textPassword"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/etPassign"
app:layout_constraintVertical_bias="0.08" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/btn_register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="#color/colorPrimary"
android:text="#string/next"
android:textColor="#FFFFFF"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/etConfirmPassign"
app:layout_constraintVertical_bias="0.132" />
<TextView
android:id="#+id/tvExist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:gravity="center_horizontal"
android:text="Already an existing member? Login"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btn_register" />
</LinearLayout>
finally this is my error log
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at universe.sk.syndriveapp.AddContacts$1.onClick(AddContacts.java:67)
at android.view.View.performClick(View.java:5619)
at android.view.View$PerformClick.run(View.java:22295)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6237)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:877)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Your addcontacts.xml doesn't have an EditText with ID etBloodgroup
The line
bloodgrp = etBloodgroup.getText().toString().trim();
causes the error.
You haven't done a findViewById() on the EditText bloodgroup before and it also does not exist in the addcontacts.xml file. If you have defined it in another xml file, you won't be able to call it in an Activity not associated with the xml source (and you cannot associate more than one xml layout file to an Activity).
So the answer is basically: Define the EditText in the xml file associated to the Activity where you are trying to handle it.

Get Value from editText in Fragment to Send With Asynctask

i have fragment for send data to server, but my edit Text always null, no error in application only cannot get the value from edit text
this is my XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<Button
android:text="Submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/submit_laporan"
android:layout_below="#+id/desc_masalah"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp" />
<TextView
android:text="Judul"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView5"
android:textSize="18sp"
android:layout_alignParentTop="true"
android:layout_marginTop="14dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:paddingLeft="10dp" />
<TextView
android:text="Deskripsi Masalah"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="19dp"
android:id="#+id/textView4"
android:textSize="18sp"
android:layout_below="#+id/judul_masalah"
android:layout_alignLeft="#+id/textView5"
android:layout_alignStart="#+id/textView5"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:paddingLeft="10dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:layout_marginTop="13dp"
android:id="#+id/desc_masalah"
android:layout_below="#+id/textView4"
android:layout_alignLeft="#+id/textView4"
android:layout_alignStart="#+id/textView4"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:paddingLeft="10dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/judul_masalah"
android:layout_marginTop="13dp"
android:layout_below="#+id/textView5"
android:layout_alignLeft="#+id/textView5"
android:layout_alignStart="#+id/textView5"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:paddingLeft="10dp" />
</RelativeLayout>
and this is my JAVA
public class Report extends Fragment{
EditText judul_masalah, desc_masalah;
Button submit_laporan;
//public Report(){}
//RelativeLayout view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.laporan, container, false);
getActivity().setTitle("Pelaporan");
/*submit_laporan.setOnClickListener(new View.OnClickListener(){
String newJudul = judul_masalah.getText().toString();
String newDeskripsi = desc_masalah.getText().toString();
#Override
public void onClick(View v){
Toast.makeText(getActivity(), newJudul,
Toast.LENGTH_LONG).show();
new sendData().execute(newJudul,newDeskripsi);
}
});*/
return V;
}
public void onViewCreated(View V, Bundle savedInstanceState){
judul_masalah = (EditText) V.findViewById(R.id.judul_masalah);
desc_masalah = (EditText) V.findViewById(R.id.desc_masalah);
submit_laporan = (Button) V.findViewById(R.id.submit_laporan);
submit_laporan.setOnClickListener(new View.OnClickListener(){
String newJudul = judul_masalah.getText().toString();
String newDeskripsi = desc_masalah.getText().toString();
#Override
public void onClick(View v){
Toast.makeText(getActivity(), newJudul,
Toast.LENGTH_LONG).show();
//new sendData().execute(newJudul,newDeskripsi);
}
});
}
public class sendData extends AsyncTask<String, String, JSONObject>{
HttpURLConnection conn;
URL url = null;
JSONParser jsonParser = new JSONParser();
private static final String TAG_INFO = "info";
private static final String LAPORAN_URL = "URL";
#Override
protected JSONObject doInBackground(String... args) {
try {
HashMap<String, String> params = new HashMap<>();
params.put("judul", args[0]);
params.put("deskripsi", args[1]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LAPORAN_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
String info = "";
if (json != null) {
//Toast.makeText(LoginActivity.this, json.toString(),
//Toast.LENGTH_LONG).show();
try {
info = json.getString(TAG_INFO);
} catch (JSONException e) {
e.printStackTrace();
}
}
if(info.equals("Success")) {
Toast.makeText(getActivity(), "Data Berhasil Disimpan",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getActivity(), "Data Gagal Disimpan",
Toast.LENGTH_LONG).show();
}
}
}
}
anyone can help me whats wrong with my code
You have to place your getText() inside the methode onClick(). Now it's outside and doesn't work.
The line :
"String newJudul = judul_masalah.getText().toString();"
after the line:
"public void onClick(View v){"

how to save spinner data and selected radio button saved to mysql database?

i cannot save selected radio buttons and spinner into mysql database? why is this?but for editText, it saves to my database.please help!
here is my submitData.php
<html>
<body>
<form action="submitData" method = "post">
Gender <input type = "radio" name="gender" value ="<?php echo $row['Gender']?>">
<input type = "radio" name="gender" value ="<?php echo $row['Gender']?>"
</form>
</body>
</html>
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$Name = $_POST['Name'];
$Age = $_POST['Age'];
$Gender=$_POST['Gender'];
$Email = $_POST['Email'];
$Phone = $_POST['Phone'];
$IncidentType = $_POST['IncidentType'];
$Description = $_POST['Description'];
require_once('dbConnect.php');
$sql = "INSERT INTO user (Name,Age,Gender,Email,Phone,IncidentType,Description) VALUES ('$Name','$Age','$Gender','$Email','$Phone','$IncidentType','$Description')";
if(mysqli_query($con,$sql)){
echo "Successfully sent";
}else{
echo "Could not send";
}
}else{
echo 'error';
}
?>
here is my FormActivity.java:
public class FormActivity extends Activity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
private static final String REGISTER_URL = "http://khaty-ismail0.rhcloud.com/phptutorial/submitData.php";
private static final String SPINNER_URL = "http://khaty-ismail0.rhcloud.com/phptutorial/spinner_data.php";
public static final String KEY_NAME= "Name";
public static final String KEY_AGE = "Age";
public static final String KEY_EMAIL = "Email";
public static final String KEY_PHONE = "Phone";
public static final String KEY_DESCRIPTION = "Description";
public static final String KEY_TICKET = "ticket_id";
public static final String KEY_SOLUTION = "solution";
public static final String JSON_ARRAY = "result";
private EditText name_eT;
private EditText age_eT;
private EditText email_eT;
private EditText phone_eT;
private EditText descr_eT;
private Button subm_btn;
private Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
name_eT = (EditText) findViewById(R.id.name_eT);
age_eT = (EditText) findViewById(R.id.age_eT);
email_eT= (EditText) findViewById(R.id.email_eT);
phone_eT= (EditText) findViewById(R.id.phone_eT);
descr_eT= (EditText) findViewById(R.id.descr_eT);
subm_btn = (Button) findViewById(R.id.subm_btn);
subm_btn.setOnClickListener(this);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), spinner.getSelectedItem().toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void registerUser(){
final String Name = name_eT.getText().toString().trim();
final String Age = age_eT.getText().toString().trim();
final String Email = email_eT.getText().toString().trim();
final String Phone = phone_eT.getText().toString().trim();
final String Description = descr_eT.getText().toString().trim();
if(TextUtils.isEmpty(Name)) {
name_eT.setError("Please enter your name");
return;
}else if(TextUtils.isEmpty(Age)) {
age_eT.setError("Please enter your age");
return;
}else if(TextUtils.isEmpty(Phone)) {
phone_eT.setError("Please enter your phone");
return;
}else if(TextUtils.isEmpty(Email)) {
email_eT.setError("Please enter your email");
return;
}else if(TextUtils.isEmpty(Description)) {
descr_eT.setError("Please enter your issue");
return;
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(FormActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(FormActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_NAME,Name);
params.put(KEY_AGE,Age);
params.put(KEY_EMAIL, Email);
params.put(KEY_PHONE, Phone);
params.put(KEY_DESCRIPTION, Description);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void onCheckboxClicked(View V) {
boolean checked = ((RadioButton) V).isChecked();
switch (V.getId()) {
case R.id.male_rb:
if (checked)
break;
case R.id.female_rb:
if (checked)
break;
}
}
#Override
public void onClick(View v) {
if(v == subm_btn){
registerUser();
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void submitData(View view) {
Intent getResponse = new Intent(this,SubmitData.class);
final int result = 1;
startActivityForResult(getResponse, result);
}
}
here is my activity_form.java:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="#color/buttonFont"
tools:context="com.example.khadijah.brucertv2.FormActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/User_info"
android:id="#+id/userInfo"
android:textSize="30sp"
android:textColor="#color/colorFont"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Name:"
android:id="#+id/name_tV"
android:textColor="#color/colorFont"
android:layout_marginTop="24dp"
android:layout_below="#+id/userInfo"
android:layout_alignLeft="#+id/userInfo"
android:layout_alignStart="#+id/userInfo" />
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Age:"
android:id="#+id/age_tV"
android:textColor="#color/colorFont"
android:layout_alignBottom="#+id/age_eT"
android:layout_alignLeft="#+id/name_tV"
android:layout_alignStart="#+id/name_tV" />
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Gender"
android:id="#+id/gender_tV"
android:textColor="#color/colorFont"
android:layout_below="#+id/age_tV"
android:layout_alignLeft="#+id/age_tV"
android:layout_alignStart="#+id/age_tV"
android:layout_marginTop="24dp" />
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Email:"
android:id="#+id/email_tV"
android:textColor="#color/colorFont"
android:layout_alignBottom="#+id/email_eT"
android:layout_alignLeft="#+id/name_tV"
android:layout_alignStart="#+id/name_tV" />
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Phone"
android:id="#+id/phone_tV"
android:textColor="#color/colorFont"
android:layout_alignBottom="#+id/phone_eT"
android:layout_alignLeft="#+id/gender_tV"
android:layout_alignStart="#+id/gender_tV" />
<EditText
android:layout_width="200dp"
android:layout_height="30dp"
android:layout_marginBottom="5dp"
android:inputType="textPersonName"
android:hint="#string/hint_required"
android:textColorHint="#color/buttonFont"
android:background="#drawable/border_style"
android:ems="10"
android:id="#+id/name_eT"
android:textColor="#color/inputFont"
android:layout_alignBottom="#+id/name_tV"
android:layout_alignRight="#+id/userInfo"
android:layout_alignEnd="#+id/userInfo" />
<EditText
android:layout_width="200dp"
android:layout_height="30dp"
android:inputType="number"
android:ems="10"
android:hint="#string/hint_required"
android:textColorHint="#color/buttonFont"
android:background="#drawable/border_style"
android:id="#+id/age_eT"
android:textColor="#color/inputFont"
android:layout_below="#+id/name_tV"
android:layout_alignRight="#+id/userInfo"
android:layout_alignEnd="#+id/userInfo" />
<EditText
android:layout_width="200dp"
android:layout_height="30dp"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/email_eT"
android:hint="#string/hint_required"
android:textColorHint="#color/buttonFont"
android:textColor="#color/inputFont"
android:background="#drawable/border_style"
android:layout_below="#+id/phone_eT"
android:layout_alignLeft="#+id/age_eT"
android:layout_alignStart="#+id/age_eT" />
<EditText
android:layout_width="200dp"
android:layout_height="30dp"
android:inputType="phone"
android:ems="10"
android:id="#+id/phone_eT"
android:layout_marginBottom="5dp"
android:textColor="#color/inputFont"
android:hint="#string/hint_required"
android:textColorHint="#color/buttonFont"
android:background="#drawable/border_style"
android:layout_below="#+id/gender_tV"
android:layout_alignLeft="#+id/email_eT"
android:layout_alignStart="#+id/email_eT" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/incident_info"
android:id="#+id/incidentInfo"
android:textColor="#color/colorFont"
android:textStyle="bold"
android:textSize="30sp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:prompt="#array/incident_type"
android:entries="#array/incident_type"
android:layout_below="#+id/incidentInfo"
android:layout_alignLeft="#+id/phone_eT"
android:layout_alignStart="#+id/phone_eT"
android:layout_alignRight="#+id/phone_eT"
android:layout_alignEnd="#+id/phone_eT"
android:spinnerMode="dropdown" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/incident_type_DD"
android:textColor="#color/colorFont"
android:id="#+id/incident_DD"
android:layout_below="#+id/incidentInfo"
android:layout_toLeftOf="#+id/spinner"
android:layout_toStartOf="#+id/spinner" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/description"
android:id="#+id/description_tV"
android:textColor="#color/colorFont"
android:layout_below="#+id/spinner"
android:layout_alignLeft="#+id/phone_tV"
android:layout_alignStart="#+id/phone_tV" />
<EditText
android:layout_width="300dp"
android:layout_height="80dp"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/descr_eT"
android:hint="#string/descr_hint"
android:textColorHint="#color/buttonFont"
android:gravity="top"
android:background="#drawable/border_style"
android:textColor="#color/inputFont"
android:layout_below="#+id/description_tV"
android:layout_alignLeft="#+id/description_tV"
android:layout_alignStart="#+id/description_tV" />
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_margin="5dp"
android:text="SUBMIT"
android:onClick="submitData"
android:textStyle="bold"
android:textSize="35sp"
android:id="#+id/subm_btn"
android:background="#drawable/custom_btn"
android:textColor="#color/buttonFont"
android:layout_alignParentBottom="true"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignLeft="#+id/phone_eT"
android:layout_alignStart="#+id/phone_eT"
android:layout_below="#+id/age_eT"
android:layout_alignRight="#+id/descr_eT"
android:layout_alignEnd="#+id/descr_eT"
android:layout_above="#+id/phone_eT"
android:weightSum="1"
android:id="#+id/radioGroup">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:text="Male"
android:id="#+id/male_rb"
android:onClick="onCheckboxClicked"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:checked="false"
android:id="#+id/female_rb"
android:onClick="onCheckboxClicked"/>
</RadioGroup>
</RelativeLayout>
here is my arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="incident_type">
<item>Fraud</item>
<item>Malicious Code</item>
<item>Spam</item>
<item>Intrusion</item>
<item>Not Sure</item>
</string-array>
</resources>
the form name is case sensitive.
use $_POST['gender'];
another thing is. where is your definition of $row? looks like it may be empty so you will not post any data.
enable error_reporting and display_errors while development help you to find such kind of errors much faster
another thing very important dont use mysql_* functions they are insecure and deprecated. have a look ad PDO instead
also use prepared statements and escape userinput.

Validations in SignUp page (Android system)

I'm trying to create a Sign Up page for my Android system. I need to check validations for it like email_id already exists ,password should contain more than eight characters ,mobile number field should contain maximum 10 digits .How can I do it?? This is my code..I use java rest webservices and Mysql database
Sign Up.java
package com.example.locationapp;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.entity.StringEntity;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
#SuppressWarnings("deprecation")
public class SignUp extends Activity {
EditText et_name, et_email, et_password, et_conf_password, et_number;
Button signup;
private Context context;
private ProgressDialog pDialog;
private CheckInternet checkNet;
private Pattern pattern;
private Matcher matcher;
private String EMAIL_PATTERN, name, email, password, conf_password, number,
toastMessage;
private boolean emailValidity, internet_status;
private final String TAG_RESPONSE_CODE = "resp_code";
ServiceHandle jsonParser = new ServiceHandle();
private String url = "http://172.30.54.89:8080/LocationBasedFramework/SignUp/RegisterUser";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
context = SignUp.this;
et_name = (EditText) findViewById(R.id.nameEditText);
et_email = (EditText) findViewById(R.id.emailEditText);
et_password = (EditText) findViewById(R.id.passwordEditText);
et_conf_password = (EditText) findViewById(R.id.conf_passwordEditText);
et_number = (EditText) findViewById(R.id.numberEditText);
signup = (Button) findViewById(R.id.signUpbutton);
checkNet = new CheckInternet();
EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
pDialog = new ProgressDialog(SignUp.this);
pDialog.setMessage("New User...");
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// CheckInternet
name = et_name.getText().toString();
email = et_email.getText().toString();
password = et_password.getText().toString();
conf_password = et_conf_password.getText().toString();
number = et_number.getText().toString();
if (email.equals("")) {
toastMessage = "Email field cannot be empty";
et_email.requestFocus(1);
} else {
emailValidity = validate(email);
if (!emailValidity) {
toastMessage = "Invalid E_mail id";
et_email.setText("");
checkNet.ToastMessage(toastMessage,
getApplicationContext());
System.out.println("onclick 3.5");
et_email.requestFocus(1);
} else {
System.out.println("-------onClick4-------");
if (password.equals("")) {
toastMessage = "Password field cannot be empty";
checkNet.ToastMessage(toastMessage, context);
et_conf_password.setText("");
et_password.requestFocus(1);
} else {
if (conf_password.equals("")) {
toastMessage = "Please confirm your password";
checkNet.ToastMessage(toastMessage, context);
et_conf_password.requestFocus(1);
} else {
if (name.equals("")) {
toastMessage = "Plaese enter your name";
checkNet.ToastMessage(toastMessage, context);
et_name.requestFocus(1);
} else {
if (number.equals("")) {
toastMessage = "Mobile No field cannot be empty";
checkNet.ToastMessage(toastMessage,
context);
et_number.requestFocus(1);
} else {
System.out
.println("-------onClick8-------");
internet_status = checkNet
.isInternetOn(context);
if (internet_status == true) {
System.out
.println("-------onClick9-------");
new CreateUser().execute();
} else {
System.out
.println("-------onClick10-------");
checkNet.ifNoInternet(context);
}
}
}
}
}
}
}
}
});
}
public boolean validate(String email) {
CharSequence hex = null;
matcher = pattern.matcher(email);
return matcher.matches();
}
class CreateUser extends AsyncTask<String, String, String> {
StringEntity se = null;
JSONObject json;
String jsonStr = "";
Boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.show();
}
protected String doInBackground(String... params) {
try {
json = new JSONObject();
json.put("name", name);
json.put("email_id", email);
json.put("password", password);
json.put("mob_num", number);
se = new StringEntity(json.toString());
System.out.println("--after se--");
String method = "post";
// int response_flag = 1;
ServiceHandle sh = new ServiceHandle();
internet_status = checkNet
.isInternetOn(getApplicationContext());
System.out.println("--internet--" + internet_status);
if (internet_status == true) {
jsonStr = sh.makeServiceCall(url, method, se);
} else {
checkNet.ifNoInternet(context);
}
if (jsonStr != null) {
json = new JSONObject(jsonStr);
int resp_code = json.getInt(TAG_RESPONSE_CODE);
if (resp_code == 0) {
name = json.getString("TAG_Name");
email = json.getString("TAG_Email");
password = json.getString("TAG_Password");
conf_password = json.getString("TAG_confPassword");
number = json.getString("TAG_Number");
}
} else {
;
}
}
catch (Exception e) {
}
return null;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
pDialog.cancel();
int response_flag = 0;
if (response_flag == 0) {
int resp_code = 0;
if (resp_code == 0) {
SharedPreferences pref = getApplicationContext()
.getSharedPreferences("userData", MODE_PRIVATE);
Editor editor = pref.edit();
editor.clear();
editor.commit();
editor.putString("name", name);
editor.putString("e_mail", email);
editor.putString("password", password);
editor.putString("conf_password", conf_password);
editor.putString("number", number);
editor.commit();
Intent intent = new Intent(SignUp.this, ViewMap.class);
startActivity(intent);
finish();
}
}
} catch (Exception e) {
}
}
}
}
This is the xml for SignUp.java .
activity_sign_up.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="com.example.locationapp.SignUp" >
<TextView
android:id="#+id/NametextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:gravity="center"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/emailtextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:gravity="center"
android:text="Email-id"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/passwordtextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:gravity="center"
android:text="Password"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/conf_passwordtextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:gravity="center"
android:text="Confirm Password"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/numbertextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="250dp"
android:gravity="center"
android:text="Mobile"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" />
<EditText
android:id="#+id/nameEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/NametextView"
android:layout_alignBottom="#+id/NametextView"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/passwordtextView"
android:background="#FFFFFF"
android:ems="10" />
<EditText
android:id="#+id/emailEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/emailtextView"
android:layout_alignBottom="#+id/emailtextView"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/passwordtextView"
android:background="#FFFFFF"
android:ems="10" />
<EditText
android:id="#+id/passwordEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/passwordtextView"
android:layout_alignBottom="#+id/passwordtextView"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/passwordtextView"
android:background="#FFFFFF"
android:ems="10"
android:inputType="textPassword" />
<EditText
android:id="#+id/conf_passwordEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/conf_passwordtextView"
android:layout_alignBottom="#+id/passwordtextView"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/conf_passwordtextView"
android:background="#FFFFFF"
android:ems="10"
android:inputType="textPassword"/>
<EditText
android:id="#+id/numberEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/numbertextView"
android:layout_alignBottom="#+id/numbertextView"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/passwordtextView"
android:background="#FFFFFF"
android:ems="10"
android:inputType="number" />
<Button
android:id="#+id/signUpbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/numbertextView"
android:layout_marginTop="34dp"
android:layout_toRightOf="#+id/emailtextView"
android:gravity="center"
android:text="SIGNUP" />
</RelativeLayout>
To check validations for it like email_id already exists
...Manage it form server
password should contain more than eight characters ,mobile number field should contain maximum 10 digits
Just pass password to following given mathod
private boolean isValidEmail(String email) {
String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}

Categories

Resources