package com.example.admin.userregistrationsample;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Some extends AppCompatActivity implements View.OnClickListener{
private EditText branch;
public TextView list,list2;
Button bt, bt1;
String temp1;
String text1,temp, usn,text;
String res;
String[] parts;
int count;
RadioGroup rg;
RadioButton[] rb;
GetJSON gj = new GetJSON();
LinearLayout mLinearLayout;
private static final String JSON_URL = "http://192.168.43.144/mini1/subject.php";
private static final String SUB_URL = "http://192.168.43.144/mini1/store.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_some);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
usn = getIntent().getStringExtra("USN");
bt = (Button) findViewById(R.id.buttonGet);
bt.setOnClickListener(this);
bt1 = (Button) findViewById(R.id.button2);
bt1.setOnClickListener(this);
branch = (EditText) findViewById(R.id.editTextId);
//invokeLogin();
}
//#Override
public void onClick(View v)
{
if (v == bt)
{
invokeLogin();
}
if (v == bt1)
{
register(temp,usn);
}
}
public void invokeLogin()
{
text = branch.getText().toString();
getJSON(text);
}
public void getJSON(String text)
{
final String urlSuffix = "?branch=" + text;
gj.execute(urlSuffix);
}
public class GetJSON extends AsyncTask<String, Void, String> {
ProgressDialog loading;
public GetJSON()
{
}
#Override
public void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Some.this, "Please Wait...", null, true, true);
}
#Override
public String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(JSON_URL + uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json).append("\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
#Override
public void onPostExecute(String s)
{
super.onPostExecute(s);
loading.dismiss();
res=s.replaceAll("\"", "");
res = res.replaceAll(",","\n ").replace('[', ' ').replace(']', ' ');
parts = res.split("\n");
count=parts.length;
mLinearLayout = (LinearLayout) findViewById(R.id.linear2);
rb = new RadioButton[count];
rg = new RadioGroup(getBaseContext());
rg.setOrientation(RadioGroup.VERTICAL);
for (int i = 0; i < count; i++)
{
rb[i] = new RadioButton(getBaseContext());
rb[i].setTextColor(Color.parseColor("#000000"));
rb[i].setTextSize(25);
rg.addView(rb[i]);
rb[i].setText(parts[i]);
}
mLinearLayout.addView(rg);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
for (int i = 0; i < group.getChildCount(); i++) {
RadioButton btn = (RadioButton) group.getChildAt(i);
if (btn.getId() == checkedId) {
temp1 = (String) btn.getText();
list2 = (TextView) findViewById(R.id.select);
list2.setText(temp);
break;
}
}
}
});
}
}
public void register(String sub ,String usn)
{
String urlSuffix = "?subject=" + sub + "&usn=" +usn;
class RegisterUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
public void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Some.this, "Please Wait", null, true, true);
}
#Override
public void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
if (s.equals("successfully registered")) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
}
#Override
public String doInBackground(String... params) {
String s = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(SUB_URL + s);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return null;
}
}
}
RegisterUser ru=new RegisterUser();
ru.execute(urlSuffix);
}
}
I have retreived the checked radio button value to variable temp. And it is appearing in the TextView but when I pass that value to register function it is not taking the value how to do that? Please anyone help..!
use the following code for use setOnCheckedChangeListener outside the async class.
protected void onPostExecute(String result) {
if(!result.equals("null"){
((your activity name) activity).parseJsonResponse(result);
pDialog.dismiss();
}
}
and add below method in your activity.
public void parseJsonResponse(String result) {
//use setOnCheckedChangeListener here.
}
Related
At the moment I can add users into the database through postman or emulator but I need to be able insert the data from actual android device .What adjustments do I have to take ? Please have a look at the code below
This is my main activity that I using in my app :
package ie.example.artur.adminapp;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.HashMap;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
EditText editTextName,editTextEmail,editTextPassword;
TextView textView;
private static final String DB_URL = "jdbc:mysql://10.3.2.51/socialmedia_website";
private static final String USER = "zzz";
private static final String PASS = "zzz";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
findViewById(R.id.layoutProgress).setVisibility(View.GONE);
textView = (TextView) findViewById(R.id.textView);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void btnConn(View view) {
findViewById(R.id.layoutProgress).setVisibility(View.VISIBLE);
final ApiClient apiClient = new ApiClient();
String email = editTextEmail.getText().toString();
String name = editTextName.getText().toString();
String password = editTextPassword.getText().toString();
HashMap<String,String> parameters = new HashMap<>();
parameters.put("email",email);
parameters.put("name",name);
parameters.put("password",password);
Call<ApiResponse> call = apiClient.loginUser(parameters);
call.enqueue(new Callback<ApiResponse>() {
#Override
public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
if(response.isSuccessful())
{
ApiResponse apiResponse = response.body();
if(apiResponse.getStatus() == 200 || apiResponse.getStatus() == 201)
{
findViewById(R.id.layoutProgress).setVisibility(View.GONE);
Send objSend = new Send();
objSend.execute("");
//Toast.makeText(MainActivity.this,"Success", Toast.LENGTH_SHORT);
textView.setText("Success.");
}
else
{
//Toast.makeText(MainActivity.this,apiResponse.getErrors(), Toast.LENGTH_SHORT);
textView.setText(apiResponse.getErrors());
}
}
else
{
findViewById(R.id.layoutProgress).setVisibility(View.GONE);
//Toast.makeText(MainActivity.this,"Invalid api response.", Toast.LENGTH_SHORT);
textView.setText("Invalid api response.");
}
}
#Override
public void onFailure(Call<ApiResponse> call, Throwable t) {
findViewById(R.id.layoutProgress).setVisibility(View.GONE);
//Toast.makeText(MainActivity.this,"No host available or please check network connectivity.", Toast.LENGTH_SHORT);
textView.setText("No host available or please check network connectivity.");
}
});
}
private class Send extends AsyncTask<String, String, String>
{
String msg = "";
String name = editTextName.getText().toString();
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();
#Override
protected void onPreExecute() {
textView.setText("Please Wait Inserting Data");
}
#Override
protected String doInBackground(String... strings) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
if (conn == null) {
msg = "Connection goes wrong";
} else {
String query = "Insert INTO users (name,email,password) VALUES('" + name+"','"+email+"','"+password+"')";
Statement stmt = conn.createStatement();
stmt.executeUpdate(query);
msg = "Inserting Successful!!";
}
conn.close();
}
catch(
Exception e
)
{
msg = "Connection goes Wrong";
e.printStackTrace();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {textView.setText(msg);}
}
}
Api client class
package ie.example.artur.adminapp;
import java.util.HashMap;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by asifj on 7/25/2017.
*/
public class ApiClient
{
private String BASE_URL = BuildConfig.BASE_URL;
ApiEndPoints apiService;
public ApiClient() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(logging); // <-- this is the important line!
Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).client(httpClient.build()).build();
apiService = retrofit.create(ApiEndPoints.class);
}
public Call<ApiResponse> loginUser(HashMap<String, String> parameters)
{
return apiService.usercreate(parameters);
}
}
If you need me to share any more class please let me know in the comments
//this is a class you'll call in you main activity
public class PostRequest extends AsyncTask<Void, Void, String> {
private String parameters;
private Context context;
public PostRequest(Context context) {
this.context = context;
Log.d("PostRequest", "Context set : " + context);
}
public void setParameters(String parameters) {
this.parameters = parameters;
Log.d("PostRequest", "Parameters set : " + parameters);
}
#Override
protected String doInBackground(Void... params) {
String response = null;
try {
URL url = new URL("url of your php script");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
OutputStreamWriter request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
response = sb.toString();
isr.close();
reader.close();
} catch (IOException e) {
// Error
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
//in your main activity you'll call it like so
PostRequest postRequest = new PostRequest(getContext());
postRequest.setParameters("param1=" + "param1value" + "¶m2=" + "param2value");
postRequest.execute();
I'm trying to retrieve data from Facebook using graph Facebook, like Profile Pic, Gender, Age, Name, ID & Link, I'm getting Facebook Profile Pic only successfully but other won't retrieved. Please help!
MainActivity.java
package com.example.facebookprofile;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.facebookprofile.pictureAsync.onImageDownloaded;
import com.example.facebookprofile.profileAsync.profileImplement;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements profileImplement, onImageDownloaded {
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClick(View view){
EditText enterUsername = (EditText) findViewById(R.id.enterUsername);
String s = "https://graph.facebook.com/" + enterUsername.getEditableText().toString();
pictureAsync picTask = new pictureAsync(this);
profileAsync task = new profileAsync(this);
picTask.execute(s + "/picture?type=large");
picTask.delegate = this;
task.delegate = this;
task.execute(s);
}
public static User parseJSON(String jsonString) throws JSONException{
JSONObject top = new JSONObject(jsonString);
String name = "NA";
if(top.has("name"))
name = top.getString("name");
String username = top.getString("username");
String id = "NA";
if(top.has("id"))
id = top.getString("id");
String gender = "NA";
if(top.has("gender"))
gender = top.getString("gender");
String link = "https://www.facebook.com/"+username;
if(top.has("link"))
link = top.getString("link");
User output = new User(name, username, id, gender, link);
return output;
}
#Override
public void update(User user) {
// TODO Auto-generated method stub
if(user == null){
Toast t = Toast.makeText(this, "Invalid username", Toast.LENGTH_SHORT);
t.show();
}
else{
TextView name = (TextView) findViewById(R.id.name);
TextView id = (TextView) findViewById(R.id.id);
TextView gender = (TextView) findViewById(R.id.gender);
TextView link = (TextView) findViewById(R.id.link);
name.setText(user.name);
id.setText(user.id);
gender.setText(user.gender);
link.setText(user.link);
}
}
#Override
public void setImage(Bitmap bitmap) {
// TODO Auto-generated method stub
if(bitmap != null){
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(bitmap);
}
}
}
pictureAsync.java
package com.example.facebookprofile;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
public class pictureAsync extends AsyncTask<String, Integer, Bitmap> {
Context context;
onImageDownloaded delegate;
public interface onImageDownloaded{
public void setImage(Bitmap bitmap);
}
public pictureAsync(Context context) {
this.context = context;
}
#Override
protected Bitmap doInBackground(String... params) {
String picUrl = params[0];
try {
URL url = new URL(picUrl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if(delegate!=null)
delegate.setImage(result);
}
}
profileAsync.java
package com.example.facebookprofile;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONException;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
public class profileAsync extends AsyncTask<String, Integer, User> {
profileImplement delegate;
Context context;
ProgressDialog dialog;
public profileAsync(Context context) {
this.context = context;
}
#Override
public void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setMessage("Loading...Please wait");
dialog.show();
}
public interface profileImplement{
public void update(User user);
}
#Override
protected User doInBackground(String... arg) {
String user = arg[0];
try {
URL url = new URL(user);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream input = connection.getInputStream();
if(input == null) return null;
Scanner networkScanner = new Scanner(input);
StringBuffer buffer = new StringBuffer();
int count = 0;
while(networkScanner.hasNext()){
String line = networkScanner.next();
count += line.length();
//publishProgress(count);
buffer.append(line);
}
networkScanner.close();
return MainActivity.parseJSON(buffer.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(User result) {
dialog.dismiss();
if(delegate != null)
delegate.update(result);
}
// protected void onProgressUpdate(Integer... values) {
// // TODO Auto-generated method stub
// super.onProgressUpdate(values);
// dialog.setMessage("downloaded: " + values[0]);
// }
}
User.java
package com.example.facebookprofile;
public class User {
String name;
String username;
String id;
String gender;
String link;
User(String name, String username , String id , String gender , String link){
this.name = name;
this.username = username;
this.id = id;
this.gender = gender;
this.link = link;
}
}
It is a feature gone deprecated.
I'm working on a network scanner, and for that I'm sending the scan to the background using an AsyncTask class. But I'm having problems implementing the onProgressUpdate() method. I'm passing an ArrayList of type string to the TaskScanNetwork class. This array will have a list of all life host on network. Any help appreciated. Thanks
package com.example.android.droidscanner;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Array;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button btnRead;
Button btnScan;
TextView textResult;
ListView listViewNode;
ArrayList<Node> listNote;
ArrayList<String> listNetwork;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRead = (Button)findViewById(R.id.readhost);
btnScan = (Button) findViewById(R.id.readnet);
textResult = (TextView)findViewById(R.id.result);
listViewNode = (ListView)findViewById(R.id.nodelist);
listNote = new ArrayList<>();
listNetwork = new ArrayList<>();
//initidating adapter for host only
ArrayAdapter<Node> adapterHost = new ArrayAdapter<Node>(
MainActivity.this,
android.R.layout.simple_list_item_1,
listNote);
listViewNode.setAdapter(adapterHost);
//initiating adapter for network scan
ArrayAdapter<String> adapterNetwork = new ArrayAdapter(
MainActivity.this,
android.R.layout.simple_list_item_1,
listNetwork);
listViewNode.setAdapter(adapterNetwork);
btnRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new TaskReadAddresses(listNote, listViewNode).execute();
}
});
btnRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new TaskScanNetwork(listNetwork, listViewNode).execute();
}
});
}
private class TaskReadAddresses extends AsyncTask<Void, Node, Void> {
ArrayList<Node> array;
ListView listView;
TaskReadAddresses(ArrayList<Node> array, ListView v){
listView = v;
this.array = array;
array.clear();
textResult.setText("querying...");
}
#Override
protected Void doInBackground(Void... params) {
readAddresses();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
textResult.setText("Done");
}
#Override
protected void onProgressUpdate(Node... values) {
listNote.add(values[0]);
((ArrayAdapter)(listView.getAdapter())).notifyDataSetChanged();
}
private void readAddresses() {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] splitted = line.split(" +");
if (splitted != null && splitted.length >= 4) {
String ip = splitted[0];
String mac = splitted[3];
if (mac.matches("..:..:..:..:..:..")) {
Node thisNode = new Node(ip, mac);
publishProgress(thisNode);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
* Asynctask to scan the network
* */
private class TaskScanNetwork extends AsyncTask<Void, ArrayList<String>, Void> {
String network;
ListView listView;
String lowBoundIp;
ArrayList<String> allNetwork;
TaskScanNetwork(ArrayList<String> array, ListView v){
listView = v;
allNetwork = array;
textResult.setText("Scanning...");
}
#Override
protected Void doInBackground(Void... params) {
scanNetwork();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
textResult.setText("Done");
}
#Override
protected void onProgressUpdate(ArrayList<String>... values) {
allNetwork.add(values);
((ArrayAdapter)(listView.getAdapter())).notifyDataSetChanged();
}
private void scanNetwork() {
try {
InetAddress localHost = InetAddress.getLocalHost();
lowBoundIp = localHost.getHostAddress();
int lastDot = lowBoundIp.lastIndexOf(".");
String host = lowBoundIp.substring(0, lastDot);
Process ping;
for(int i = 1; i < 255; i++) {
host = host + "." + Integer.toString(i);
try {
ping = Runtime.getRuntime().exec("ping -n 1 " + host);
int returnVal = ping.waitFor();
if(returnVal == 0) {
publishProgress(allNetwork);
}
}
catch(Exception ex) {
ex.printStackTrace();
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I am new for Android i want to know how to connect database.I saw one video in you tube and i follow hole video but its not working.i don't know where i made mistake. please help me.from one week an words i'm trying but now also i'm not getting solution please help me stack over flow.
class ServerRequests {
ProgressDialog progressDialog;
public static final int CONNECTION_TIMEOUT=1000*15;
public static final String
SERVER_ADDRESS="http://192.168.1.11/myfolder/new1.php";
public ServerRequests(Context context){
progressDialog=new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("processing");
progressDialog.setMessage("please wait.....");
}
public void storeUserDataInBackground(User user,GetUserCallbackuserCallback{
progressDialog.show();
new StoreUserDataAsyncTask(user,userCallback).execute();
}
public void fetchUserDataInBackground(User user,GetUserCallback callBack){
progressDialog.show();
new fetchUserDataAsynctask(user,callBack).execute();
}
public class StoreUserDataAsyncTask extends AsyncTask<Void,Void,Void>{
User user;
GetUserCallback userCallback;
public StoreUserDataAsyncTask(User user,GetUserCallback userCallback){
this.user=user;
this.userCallback=userCallback;
}
#Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair>dataToSend=new ArrayList<>();
dataToSend.add(new BasicNameValuePair("name",user.name));
dataToSend.add(new BasicNameValuePair("age",user.age + ""));
dataToSend.add(new BasicNameValuePair("username",user.username));
dataToSend.add(new BasicNameValuePair("password",user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams,CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams,CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "Register.php");
try{
post.setEntity(new URLEncoderFormEntity(dataToSend));
client.execute(post);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onpostExecute(Void aVoid){
progressDialog.dismiss();
userCallback.done(null);
super.onPostExecute(aVoid);
}
}
public fetchUserDataAsyncTask extends AsyncTask<Void,Void,User>{
User user;
GetUserCallback userCallback;
public fetchUserDataAsyncTask(User user,GetUserCallback userCallback){
this.user=user;
this.userCallback = userCallback;
}
#Override
protected User doInBackground(Void... params){
ArrayList<NameValuePair>dataToSend=new ArrayList<>();
dataToSend.add(new BasicNameValuePair("username",user.username));
dataToSend.add(new BasicNameValuePair("password",user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");
User returnedUser=null;
try{
post.setEntity(new URLEncoderFormEntity(dataToSend));
HttpResponce httpResponce=client.execute(post);
HttpEntity entity=httpResponce.getEntity();
String result= EntityUtils.toString(entity);
JSONObject jObject=new JSONObject(result);
if (jObject.length()==0){
user=null;
}else{
String name=jObject.getString("name");
int age =jObject.getInt("age");
returnedUser=new User(name,age,user.username,user.password);
}
}catch (Exception e){
e.printStackTrace();
}
return returnedUser;
}
#Override
protected void onPostExecute(User returnedUser){
progressDialog.dismiss();
userCallback.done(null);
super.onPostExecute(returnedUser);
}
}
}
enter code here
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
Button blogin;
EditText etusername,etpassword;
TextView tvregister;
UserLocalStore userLocalStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
etusername=(EditText)findViewById(R.id.username_edit);
etpassword=(EditText)findViewById(R.id.password_edit);
blogin=(Button)findViewById(R.id.login_button);
tvregister=(TextView)findViewById(R.id.tv_register);
blogin.setOnClickListener(this);
tvregister.setOnClickListener(this);
userLocalStore=new UserLocalStore(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.login_button:
String username=etusername.getText().toString();
String password=etpassword.getText().toString();
User user=new User(username,password);
authenticate(user);
userLocalStore.storeUserData(user);
userLocalStore.setUserLoggedIn(true);
break;
case R.id.tv_register:
startActivity(new Intent(this,RegisterActivity.class));
break;
}
}
private void authenticate(User user) {
ServerRequests serverRequests = new ServerRequests(this);
serverRequests.fetchUserDataInBackground(user, new GetUserCallback() {
#Override
public void done(User returnedUser) {
if (returnedUser == null) {
showErrorMessage();
}else {
logUserIn(returnedUser);
}
}
});
}
private void showErrorMessage() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(LoginActivity.this);
dialogBuilder.setMessage("Incorrect user details");
dialogBuilder.setPositiveButton("ok", null);
dialogBuilder.show();
}
private void logUserIn(User returnedUser){
userLocalStore.storeUserData(returnedUser);
userLocalStore.setUserLoggedIn(true);
startActivity(new Intent(this,MainActivity.class));
}
}
Here is the link which you can refer for fetching data from server.
For Creating Web Service using PHP Click here
<?php
include("connect.php");
$result="";
//get data from users (name for user variable is p1 and p2
//here I am stroing this value to par1 and par2
//method i am using is GET
$par1=$_GET['p1'];
$par2=$_GET['p2'];
$eve = "select * from table where field1='$par1' and field2='$par2'";
$re = mysql_query($eve);
$response = array();
$posts = array();
while($rt = mysql_fetch_array($re))
{
$f1=$rt['field1'];
$f2=$rt['field2'];
break;
}
$posts[] = array('p1'=> $f1,'p2'=> $f2);
$response['posts'] = $posts;
echo stripslashes(json_encode( array('item' => $posts)));
?>
For AsyncTask Example Click here
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Login extends AppCompatActivity {
boolean remember;
private ProgressDialog pDialog;
public static final String PREFS_NAME = "Preference";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
((Button) findViewById(R.id.btnlogin)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Login Validation
try {
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Verifying...");
pDialog.show();
LoginVerifyTask g = new LoginVerifyTask();
g.execute(((EditText) findViewById(R.id.mobile)).getText().toString(), ((EditText) findViewById(R.id.password)).getText().toString());
} catch (Exception e) {
Log.e("cs", "catch error");
}
}
});
((TextView) findViewById(R.id.newuserregistrationtxtview)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Registration1.class);
startActivity(i);
}
});
}
public class LoginVerifyTask extends AsyncTask<String, Void, String>
{
String u,p;
void LoginActivity(String s)
{
}
#Override
protected void onPostExecute(String json) {
// TODO Auto-generated method stub
pDialog.dismiss();
pDialog = null;
if (json == null)
{
return;
}
String csv="";
try {
JSONObject js = new JSONObject(json);
JSONArray user = js.getJSONArray("item");
for(int i=0;i<user.length();i++)
{
JSONObject j2 = user.getJSONObject(i);
//received data
String result = j2.get("p1").toString();
break;
}
}
catch(JSONException js)
{
}
return;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
u = params[0];
p = params[1];
String tempdata="";
String buffer="";
try
{
URL url = new URL("http://websitename.com/folder/webservice.php?p1=" + params[0].replace(" ", "%20") + "&p2=" + params[1].replace(" ", "%20"));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
InputStream is = conn.getInputStream();
//buffer = new String();
if(is==null)
{
return tempdata;
}
else
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line="";
while( (line = reader.readLine())!=null)
{
buffer += line;
}
return buffer;
}
}
catch(Exception e)
{
Log.e("cs", e.toString());
}
return buffer;
}
}
}
I have a form having one edittext and an autocompleteview. And a button to search things based on this form. In this form I can either give value in edittext and autocompleteview may be empty and vice versa. On this basis I have passed value of these view to another activity where I made a webservice call and then fetch result.
This is activity where these view are presents:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patient_section);
getSupportActionBar().hide();
searchByNameEditText = (EditText) findViewById(R.id.searchByNameEditText);
searchByAddressEditText = (EditText) findViewById(R.id.searchByAddressEditText);
searchButton = (Button) findViewById(R.id.searchButton);
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.selectStateSpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line,
getResources().getStringArray(R.array.state_arrays));
autoCompleteTextView.setAdapter(adapter);
patientUtilityButton = (Button) findViewById(R.id.patientUtilityButton);
patientUtilityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(PatientSectionActivity.this, patientUtilityButton);
popupMenu.getMenuInflater().inflate(R.menu.patient_utility_button_popmenu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
String patientUtilityMenuItem = item.toString();
patientUtilityButton.setText(patientUtilityMenuItem);
return true;
}
});
popupMenu.show();
}
});
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedStateValue = (String) parent.getItemAtPosition(position);
}
});
doctorName = searchByNameEditText.getText().toString();
// Search Button
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!selectedStateValue.equals(" ") || doctorName.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("State Name", selectedStateValue);
startActivity(intent);
} else if (!doctorName.equals(" ") || selectedStateValue.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("Name", doctorName);
startActivity(intent);
}
}
});
}
And in other activity, I get these extras from intent and make webservice call in AsyncTask but my app is crashing. Please any one help me as I am new in android.
This is my other activity
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class DoctorNameActivity extends ActionBarActivity {
ArrayAdapter<String> doctorAdapter;
ListView listView;
ProgressBar progressBar;
String doctorName;
String selectedStateValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_name);
progressBar = (ProgressBar) findViewById(R.id.progress);
listView = (ListView) findViewById(R.id.listView);
Intent intent = getIntent();
selectedStateValue = intent.getStringExtra("State Name");
doctorName = intent.getStringExtra("Name");
if (!selectedStateValue.equals(" ") || doctorName.equals(" ")){
FetchDoctorName fetchDoctorName = new FetchDoctorName();
fetchDoctorName.execute(selectedStateValue);
}else if (!doctorName.equals(" ") || selectedStateValue.equals(" ")){
FetchDoctorName fetchDoctorName = new FetchDoctorName();
fetchDoctorName.execute(doctorName);
}
}
private class FetchDoctorName extends AsyncTask<String, Void, String[]>{
private final String LOG_TAG = FetchDoctorName.class.getSimpleName();
public String[] parseDoctorName(String jsonString) throws JSONException{
final String DOCTOR_NAME_ARRAY = "name";
JSONObject object = new JSONObject(jsonString);
JSONArray array = object.getJSONArray(DOCTOR_NAME_ARRAY);
String[] doctorNamesResult = new String[array.length()];
for (int i = 0 ; i < array.length(); i++){
String doctorName = array.getString(i);
Log.v(LOG_TAG, doctorName);
doctorNamesResult[i] = doctorName;
}
return doctorNamesResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(ProgressBar.VISIBLE);
}
#Override
protected String[] doInBackground(String... params) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String doctorJsonString = null;
try {
final String BASE_URL = "http://mycityortho.com/display_result.php";
final String NAME_PARAM = "name";
final String STATE_PARAM = "state";
URL url = null;
if (params[0].equals(doctorName)){
Uri uri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(NAME_PARAM, params[0])
.build();
url = new URL(uri.toString());
Log.v(LOG_TAG, url.toString());
}else if (params[0].equals(selectedStateValue)){
Uri uri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(STATE_PARAM, params[0])
.build();
url = new URL(uri.toString());
Log.v(LOG_TAG, url.toString());
}
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
doctorJsonString = buffer.toString();
Log.v(LOG_TAG, doctorJsonString);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return parseDoctorName(doctorJsonString);
}catch (JSONException e){
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
progressBar.setVisibility(ProgressBar.GONE);
if (result != null){
doctorAdapter = new ArrayAdapter<>(DoctorNameActivity.this, android.R.layout.simple_list_item_1, result);
listView.setAdapter(doctorAdapter);
}
}
}
As per your code you are sending only one value in intent that is "State Name" or "Name" but in other activity you are trying to receive both value, that why you get null pointer exception.
So use the following code to solve this error.
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!selectedStateValue.equals(" ") || doctorName.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("State Name", selectedStateValue);
intent.putExtra("Name", " ");
startActivity(intent);
} else if (!doctorName.equals(" ") || selectedStateValue.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("State Name", " ");
intent.putExtra("Name", doctorName);
startActivity(intent);
}
}
});