I try to send some text to web and this is my codes , but it's not support utf8
For example آرین Show ????
how can I delete this problem?!
This is supported English ...
FragmentForm
package com.kamalan.phpandroidapi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
public class FragmentForm extends Fragment {
// An interface to display or dismiss of ProgressBar
public interface OnSendingRequestToServer {
public void DisplayLoding(boolean setVisibility);
}
private final String TAG = "FragmentForm";
private OnSendingRequestToServer onRequestToServer;
private Context context;
private EditText etName;
private EditText etComment;
private RatingBar ratingBar;
private ImageButton ibSubmit;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
onRequestToServer = (OnSendingRequestToServer) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnConnectingToServer interface.");
}
context = activity.getApplicationContext();
Log.d(TAG, "Fragment attached to activity.");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_form, container, false);
etName = (EditText) view.findViewById(R.id.etName);
etComment = (EditText) view.findViewById(R.id.etComment);
ratingBar = (RatingBar) view.findViewById(R.id.ratingBar);
ibSubmit = (ImageButton) view.findViewById(R.id.ibSubmit);
//TextView tvcm = (TextView) view.findViewById(R.id.tvComment);
Log.d(TAG, "Fragment created.");
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ibSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String strName = etName.getText().toString().trim();
if(strName.length() <= 0) {
Toast.makeText(context, "نام خود را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
String strComment = etComment.getText().toString().trim();
if(strComment.length() <= 0) {
Toast.makeText(context, "متن جک را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
int rate = (int) ratingBar.getRating();
if(rate <= 0) {
Toast.makeText(context, "امتیاز جکتان را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
String deviceId = getDeviceId();
new SendFormTask(deviceId, strName, rate, strComment).execute();
}
private TextView findViewById(int tvcomment) {
// TODO Auto-generated method stub
return null;
}
});
}
private String getDeviceId() {
return Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
}
/*----------------------------------------------------------------------------
* This method is responsible for creating another thread in parallel with
* main UI thread in order to send a request to server and get data (if any).
* ---------------------------------------------------------------------------*/
public class SendFormTask extends AsyncTask<Void, Void, Boolean> {
String deviceId, name, comment;
int rate;
SendFormTask(String deviceId, String strName, int rate, String strComment) {
this.deviceId = deviceId;
this.name = strName;
this.rate = rate;
this.comment = strComment;
}
#Override
protected void onPreExecute() {
Log.d(TAG, "SendFormTask is about to start...");
onRequestToServer.DisplayLoding(true);
}
#Override
protected Boolean doInBackground(Void... params) {
boolean status = false;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(LinkManager.getFormAPI(deviceId, name, rate, comment));
Log.d(TAG, "Try to open: " + url.toString());
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
Log.d(TAG, "Response code is: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
if (in != null) {
StringBuilder strBuilder = new StringBuilder();
// Read character by character
int ch = 0;
while ((ch = in.read()) != -1)
strBuilder.append((char) ch);
// get returned message and show it
String response = strBuilder.toString();
Log.d("Server response:", response);
if(response.equalsIgnoreCase("1"))
status = true;
}
in.close();
}
}
catch(MalformedURLException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return status;
}
#Override
protected void onPostExecute(Boolean result) {
Log.d(TAG, "SendFormTask finished its task.");
onRequestToServer.DisplayLoding(false);
if(result)
Toast.makeText(context, "جک شما ارسال شد, منتظر تایید آن باشید", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "جک شما ارسال شد , منتظر تایید آن باشید", Toast.LENGTH_LONG).show();
}
}
}
and LinkManager.java for link to web
public class LinkManager {
private final static String API_FORM = "http://example.com/sendjoke.php?p1=###&p2=####&p3=#####&p4=######";
private final static String API_Comment = "http://example.com/index.php?p1=###";
public static String getFormAPI(String deviceId, String name, int rate, String comment) {
String url = API_FORM;
url = url.replaceAll("###", deviceId);
url = url.replaceAll("####", name);
url = url.replaceAll("#####", Integer.toString(rate));
url = url.replaceAll("######", comment);
url = url.replaceAll(" ", "%20");
return url;
}
public static String getCommentAPI(String deviceId) {
String url = API_Comment;
url = url.replaceAll("###", deviceId);
return url;
}
}
Please Help me.
Sry My English is bad.
Try to use urlencoding. like :HttpGet get = new HttpGet(URLEncoder.encode(url,"UTF-8"));
url is the specific urllink.And If You want to use httppost, encode the entity before setEntity
Related
ElementAdapter class
package com.example.sierendeelementeninbreda;
import android.content.Context;
import android.view.ViewGroup;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class ElementAdapter extends RecyclerView.Adapter<ElementAdapter.ViewHolder> {
private static final String TAG = ElementAdapter.class.getSimpleName();
private List<Element> mElements = new ArrayList<>();
private final ElementOnClickHandler mElementClickHandler;
public ElementAdapter(List<Element> mElements, ElementOnClickHandler mElementClickHandler) {
this.mElements = mElements;
this.mElementClickHandler = mElementClickHandler;
}
#NonNull
#Override
public ElementAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
Log.v(TAG, "++++++++ onCreateViewHolder - viewGroup-class: " + viewGroup.getClass().getSimpleName());
Log.v(TAG, "++++++++ onCreateViewHolder - viewGroup-resourceName: " + viewGroup.getContext().getResources().getResourceName(viewGroup.getId()));
Log.v(TAG, "++++++++ onCreateViewHolder - viewGroup-resourceEntryName: " + viewGroup.getContext().getResources().getResourceEntryName(viewGroup.getId()));
Context context = viewGroup.getContext();
LayoutInflater inflator = LayoutInflater.from(context);
// create a new view
View elementListItem = inflator.inflate(R.layout.element_item, viewGroup, false);
ElementAdapter.ViewHolder viewHolder = new ViewHolder(elementListItem);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Log.v(TAG, "++++ onBindViewHolder-type: " + holder.getClass().getSimpleName());
holder.title.setText(mElements.get(position).getTitle());
holder.geographicalLocation.setText(mElements.get(position).getGeographicalLocation());
holder.identificationNumber.setText(mElements.get(position).getIdentificationNumber());
Picasso.get()
.load(mElements.get(position).getImage())
.into(holder.image);
}
#Override
public int getItemCount() {
return mElements.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//one drinkItem has 3 views
// Provide a reference to each view in the drinkItem
private ImageView image;
private TextView title;
private TextView geographicalLocation;
private TextView identificationNumber;
public ViewHolder(View listItemView) {
super(listItemView);
title = (TextView) listItemView.findViewById(R.id.element_item_name);
geographicalLocation = (TextView) listItemView.findViewById(R.id.element_Location);
identificationNumber = (TextView) listItemView.findViewById(R.id.element_idNumber);
image = (ImageView) listItemView.findViewById(R.id.element_item_imageview);
// image.setOnClickListener(this);
// name.setOnClickListener(this);
// description.setOnClickListener(this);
// listItemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int itemIndex = getAdapterPosition();
mElementClickHandler.onElementClick(view, itemIndex);
}
}
}
NetworkUtils class
package com.example.sierendeelementeninbreda;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Scanner;
public class NetworkUtils extends AsyncTask<String, Void, String> {
private static final String TAG = NetworkUtils.class.getSimpleName();
private OnElementApiListener listener;
private final static String url = "https://services7.arcgis.com/21GdwfcLrnTpiju8/arcgis/rest/services/Sierende_elementen/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json";
public NetworkUtils(OnElementApiListener listener) {
this.listener = listener;
}
#Override
protected String doInBackground(String... input) {
//De methode begint met een log zodat je kunt zien wat er gebeurt in de run.
Log.d(TAG, "doInBackground was called");
String response = null;
HttpURLConnection httpURLConnection = null;
// ToDo: Url maken op basis van internet adres
try {
URL mUrl = new URL(url);
URLConnection mConnection = mUrl.openConnection();
httpURLConnection = (HttpURLConnection) mConnection;
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.connect();
int responseCode = httpURLConnection.getResponseCode();
if(responseCode != HttpURLConnection.HTTP_OK){
Log.e(TAG, "Aanroep naar de server is mislukt!");
} else {
InputStream in = httpURLConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
response = scanner.next();
}
}
Log.d(TAG, response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(httpURLConnection != null)
httpURLConnection.disconnect();
}
return response;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d(TAG, "onPreExecute: ");
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
Log.i(TAG, "createElementFromJson called");
ArrayList<Element> elements = new ArrayList<>();
if (response == null || response.equals("")) {
Log.e(TAG, "onPostExecute: empty response!");
return;
}
try {
JSONObject jsonResults = new JSONObject(response);
JSONArray elementList = jsonResults.getJSONArray("features");
Log.d(TAG, "onPostExecute: " + jsonResults);
Log.i(TAG, "elementArray length = " + elementList.length());
for(int i = 0; i < elementList.length(); i++) {
JSONObject element = elementList.getJSONObject(i);
//all info
JSONObject elementAttributes = element.getJSONObject("attributes");
String image = elementAttributes.getString("URL");
String title = elementAttributes.getString("AANDUIDINGOBJECT");
String geographicalLocation = elementAttributes.getString("GEOGRAFISCHELIGGING");
String identificationNumber = elementAttributes.getString("IDENTIFICATIE");
Element element_item = new Element(title, geographicalLocation, identificationNumber);
element_item.setImage(image);
elements.add(element_item);
Log.i(TAG, String.valueOf(elements.size()));
}
listener.onElementAvailable(elements);
} catch (JSONException e) {
e.printStackTrace();
}
}
public interface OnElementApiListener {
void onElementAvailable(ArrayList<Element> elements);
}
MainActivity class
package com.example.sierendeelementeninbreda;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
implements View.OnClickListener,NetworkUtils.OnElementApiListener,
ElementOnClickHandler{
private static String TAG = MainActivity.class.getName();
private final static String url = "https://services7.arcgis.com/21GdwfcLrnTpiju8/arcgis/rest/services/Sierende_elementen/FeatureServer/0/query?where=1=1&outFields=&outSR=4326&f=json";
private ArrayList<Element> mElementList;
private RecyclerView elementRecyclerView;
private ElementAdapter mElementAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
elementRecyclerView= findViewById(R.id.recyclerView_element_list);
elementRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mElementAdapter = new ElementAdapter(mElementList,this);
elementRecyclerView.setAdapter(mElementAdapter);
// Start background task
NetworkUtils networkingTask = new NetworkUtils(this);
networkingTask.execute(url);
}
#Override
public void onElementAvailable(ArrayList<Element> elements) {
Log.i(TAG, "elements = " + elements.size());
this.mElementList = new ArrayList<>();
mElementList.clear();
mElementList.addAll(elements);
mElementAdapter.notifyDataSetChanged();
Log.i(TAG, "new elements = " + mElementList.size());
}
#Override
public void onElementClick(View view, int itemIndex) {
Log.v(TAG, "clicked on " + view.getClass().getSimpleName());
int viewId = view.getId();
Context context = this;
String toastMessage = "";
// if (viewId == R.id.product_imageview) {
// toastMessage = "clicked on image of drink item";
// } else if (viewId == R.id.product_item_name || viewId == R.id.product_item_description) {
// toastMessage = "clicked on name or description of drink item";
// } else if (viewId == R.id.product_list_item) {
// toastMessage = "clicked on drink list-item nr: " + itemIndex;
// }
Toast.makeText(context, toastMessage, Toast.LENGTH_LONG)
.show();
}
#Override
public void onClick(View v) {
}
}
Error
D/NetworkUtils: onPreExecute:
D/NetworkUtils: doInBackground was called
D/HostConnection: HostConnection::get() New Host Connection established 0xd4a13c30, tid 27630
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sierendeelementeninbreda, PID: 27595
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at com.example.sierendeelementeninbreda.ElementAdapter.getItemCount(ElementAdapter.java:64)
at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:4044)
at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3849)
at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4404)
at android.view.View.layout(View.java:21912)
at android.view.ViewGroup.layout(ViewGroup.java:6260)
That is the error I get when I run the app, I have tried solving this by looking things up but it is not working. The NullPointerException happens in line 64 of my adapter class. The app basically uses an API to get data from a site and then showcases it in a recylerView.
your not init mElementList before passed to adapter so when adapter call size method
will throw null pointer
edit your code here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
elementRecyclerView= findViewById(R.id.recyclerView_element_list);
elementRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// init mElementList here
mElementList = new ArrayList<>();
mElementAdapter = new ElementAdapter(mElementList,this);
elementRecyclerView.setAdapter(mElementAdapter);
// Start background task
NetworkUtils networkingTask = new NetworkUtils(this);
networkingTask.execute(url);
}
It is always better to do null check
#Override
public int getItemCount() {
if(mElements!=null)
return mElements.size();
else return 0
}
and initialize mElements in constructor
I'm trying to build a simple phonebook application where I can perform a search and an API will return the information. So far this is the part that I've got working.
I also want incoming caller to be identified with the same API, that would require the incoming number from Broastcastreceiver to be put into the API query and the returned information should be displayed in a toast. This is the part I'm having problems with.
So far this is what I have. Apologize if its really messy, this is what I've been playing around with recently and made small adjustments. Also its alot of copy-paste, I'm a beginner at java/Android and trying to learn.
HttpHandler.java
package se.xx.api_test;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class HttpHandler extends PhoneCallReceiver {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
PhoneCallReceiver.java
package se.xx.api_test;
import java.util.Date;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
import android.util.Log;
public class PhoneCallReceiver extends BroadcastReceiver {
//The receiver will be recreated whenever android feels like it. We need a static variable to remember data between instantiations
private static int lastState = TelephonyManager.CALL_STATE_IDLE;
private static Date callStartTime;
private static boolean isIncoming;
public static String savedNumber; //because the passed incoming is only valid in ringing
#Override
public void onReceive(Context context, Intent intent) {
//We listen to two intents. The new outgoing call only tells us of an outgoing call. We use it to get the number.
if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
}
else{
String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
int state = 0;
if(stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)){
state = TelephonyManager.CALL_STATE_IDLE;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
state = TelephonyManager.CALL_STATE_OFFHOOK;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)){
state = TelephonyManager.CALL_STATE_RINGING;
}
onCallStateChanged(context, state, number);
}
}
//Derived classes should override these to respond to specific events of interest
protected void onIncomingCallStarted(Context ctx, String number, Date start){}
protected void onOutgoingCallStarted(Context ctx, String number, Date start){}
protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end){}
protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end){}
protected void onMissedCall(Context ctx, String number, Date start){}
//Deals with actual events
//Incoming call- goes from IDLE to RINGING when it rings, to OFFHOOK when it's answered, to IDLE when its hung up
//Outgoing call- goes from IDLE to OFFHOOK when it dials out, to IDLE when hung up
public void onCallStateChanged(Context context, int state, String number) {
if(lastState == state){
//No change, debounce extras
return;
}
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
isIncoming = true;
callStartTime = new Date();
savedNumber = number;
onIncomingCallStarted(context, number, callStartTime);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
//Transition of ringing->offhook are pickups of incoming calls. Nothing done on them
if(lastState != TelephonyManager.CALL_STATE_RINGING){
isIncoming = false;
callStartTime = new Date();
onOutgoingCallStarted(context, savedNumber, callStartTime);
}
break;
case TelephonyManager.CALL_STATE_IDLE:
//Went to idle- this is the end of a call. What type depends on previous state(s)
if(lastState == TelephonyManager.CALL_STATE_RINGING){
//Ring but no pickup- a miss
onMissedCall(context, savedNumber, callStartTime);
}
else if(isIncoming){
onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
}
else{
onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());
}
break;
}
lastState = state;
}
}
MainActivity.java
package se.xx.api_test;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.HashMap;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
public class MainActivity extends AppCompatActivity {
private TextView tv;
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
tv = (TextView) findViewById(R.id.textInput);
Button queryButton = (Button) findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
// TODO: handle exception
}
contactList.clear();
new GetContacts().execute();
}
});
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//Toast.makeText(MainActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
String id = tv.getText().toString();
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2/api/api.php?id="+id;
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 contacts = jsonObj.getJSONArray("data");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String namn = c.getString("namn");
String avdelning = c.getString("avdelning");
//String telnr = c.getString("telnr");
//JSONObject data = jsonObj.getJSONObject("data");
//String namn = data.getString("namn");
//String avdelning = data.getString("avdelning");
//String telnr = data.getString("telnr");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobil = phone.getString("mobil");
String telnr = phone.getString("telnr");
//String office = phone.getString("office");
// tmp hash map for single contact
//HashMap<String, String> contact = new HashMap<>();
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("namn", namn);
contact.put("avdelning", avdelning);
contact.put("mobil", mobil);
contact.put("telnr", telnr);
//contact.put("phone", phone);
//contact.put("namn", namn);
//contact.put("avdelning", avdelning);
//contact.put("telnr", telnr);
// adding contact to contact list
contactList.add(contact);
}
} 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(MainActivity.this, contactList,
R.layout.list_item, new String[]{ "namn","avdelning","mobil", "telnr"},
new int[]{R.id.email, R.id.mobile, R.id.mobil, R.id.telnr});
lv.setAdapter(adapter);
}
}
}
CallReceiver.java (this is what I've been playing around with)
package se.xx.api_test;
import java.util.Date;
import java.util.HashMap;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.TextView;
import android.widget.RelativeLayout;
import android.view.ViewGroup;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import android.widget.ListAdapter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import java.lang.String;
import android.telephony.TelephonyManager;
public class CallReceiver extends PhoneCallReceiver {
#Override
public void onIncomingCallStarted(Context ctx, String number, Date start) {
final String phnr = String.valueOf(R.id.mobile);
Toast toast = Toast.makeText(ctx.getApplicationContext(), , Toast.LENGTH_SHORT);
ViewGroup group = (ViewGroup) toast.getView();
TextView messageTextView = (TextView) group.getChildAt(0);
messageTextView.setTextSize(25);
toast.show();
}
#Override
public void onOutgoingCallStarted(Context ctx, String number, Date start) {
}
#Override
protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end) {
}
#Override
protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end) {
}
#Override
protected void onMissedCall(Context ctx, String number, Date start) {
}
private class APICall extends MainActivity {
String number = getIntent().getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
protected Void doInBackground(Void... arg0) {
String TAG = MainActivity.class.getSimpleName();
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2/api/api.php?id="+number;
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 contacts = jsonObj.getJSONArray("data");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
final String namn = c.getString("namn");
String avdelning = c.getString("avdelning");
//String telnr = c.getString("telnr");
//JSONObject data = jsonObj.getJSONObject("data");
//String namn = data.getString("namn");
//String avdelning = data.getString("avdelning");
//String telnr = data.getString("telnr");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobil = phone.getString("mobil");
String telnr = phone.getString("telnr");
//String office = phone.getString("office");
// tmp hash map for single contact
//HashMap<String, String> contact = new HashMap<>();
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("namn", namn);
contact.put("avdelning", avdelning);
contact.put("mobil", mobil);
contact.put("telnr", telnr);
//contact.put("phone", phone);
//contact.put("namn", namn);
//contact.put("avdelning", avdelning);
//contact.put("telnr", telnr);
// adding contact to contact list
contactList.add(contact);
}
} 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;
}
}
}
which part you got an error ?
with your Api ? or while receive you phone number from service ?
put your error to clarify the situation
Here are my Android and PHP codes available. I am able to compare the password and Login successfully if password is in form of normal String. But when I am entering the password in encrypted format I am not able to compare the password value.And therefore not able to Login Successfully.
SignUpActivity.Java
package com.kezinking.nupur.kezinking;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static android.R.attr.id;
/**
* Created by Nupur on 8/2/2016.
*/
public class SignupActivity extends AppCompatActivity {
private static final String TAG ="" ;
TextView link_login;
Button btn_signup;
EditText input_username;
EditText input_email;
EditText input_password;
String username;
String email;
String password;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
link_login = (TextView) findViewById(R.id.link_login);
btn_signup = (Button) findViewById(R.id.btn_signup);
input_username=(EditText) findViewById(R.id.input_username);
input_email=(EditText) findViewById(R.id.input_email);
input_password=(EditText) findViewById(R.id.input_password);
link_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SignupActivity.this, LoginActivity.class);
startActivity(intent);
SignupActivity.this.getIntent();
}
});
btn_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
username = input_username.getText().toString();
email= input_email.getText().toString();
password = input_password.getText().toString();
SignUp();
}
});
}
public void SignUp() {
if (!validate()) {
onSignupFailed();
return;
}else{
insert(username,email,password);
}
}
public void insert(final String username, final String email,final String password){
class SendPostReqAsynTask extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... params) {
String paramUsername=params[0];
String paramPassword=params[1];
//String username = etUsername.getText().toString();
//String password = etPassword.getText().toString();
List<NameValuePair> nameValuePairs= new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("username",username));
nameValuePairs.add(new BasicNameValuePair("email",email));
nameValuePairs.add(new BasicNameValuePair("password",password));
try{
HttpClient httpClient = new DefaultHttpClient();
// HttpGet request = new HttpGet("http://www.example.com");
HttpPost httpPost = new HttpPost("http://kezinking.com/SignUpAndroid");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response= httpClient.execute(httpPost);
HttpEntity entity= response.getEntity();
int i =response.getStatusLine().getStatusCode();
System.out.println(i);
onSignupSuccess();
}catch(ClientProtocolException e){
}catch (IOException e){
}
return "Success";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
TextView textViewResult = (TextView) findViewById(R.id.txtResultCheck);
textViewResult.setText("Successfully Registered");
}
}
SendPostReqAsynTask sendPostReqAsynTask=new SendPostReqAsynTask();
sendPostReqAsynTask.execute(username,password);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onSignupSuccess() {
//btn_signup.setEnabled(true);
Intent intent=new Intent(SignupActivity.this,MainActivity.class);
startActivity(intent);
SignupActivity.this.getIntent();
}
public void onSignupFailed() {
Toast.makeText(getBaseContext(), "Failed to Register", Toast.LENGTH_LONG).show();
// btn_signup.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String username = input_username.getText().toString();
String email = input_email.getText().toString();
String password = input_password.getText().toString();
if (username.isEmpty() || username.length() < 3) {
input_username.setError("at least 3 characters");
valid = false;
} else {
input_username.setError(null);
}
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
input_email.setError("enter a valid email address");
valid = false;
} else {
input_email.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
input_password.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
input_password.setError(null);
}
return valid;
}
}
LoginActivity.Java
package com.kezinking.nupur.kezinking;
import android.animation.ObjectAnimator;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Space;
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.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Nupur on 8/2/2016.
*/
public class LoginActivity extends AppCompatActivity {
public static final String MY_JSON = "MY_JSON";
private static final String JSON_URL = "http://kezinking.com/AndroidLogin";
EditText input_email, input_password;
Button btn_login, btnContactUs, btnWorkhr, btnDeltime, btnMoneyBack;
TextView link_signup, textViewJSON, txtcheck;
private static Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_login = (Button) findViewById(R.id.btn_login);
link_signup = (TextView) findViewById(R.id.link_signup);
input_email = (EditText) findViewById(R.id.input_email);
input_password = (EditText) findViewById(R.id.input_password);
textViewJSON = (TextView) findViewById(R.id.textViewJSON);
// value=(TextView)findViewById(R.id.value);
txtcheck = (TextView) findViewById(R.id.txtcheck);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login();
}
});
link_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
startActivity(intent);
LoginActivity.this.getIntent();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void login() {
if (!validate()) {
onLoginFailed();
return;
} else {
getJSON(JSON_URL);
}
}
public void getJSON(String url) {
class GetJSON extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(LoginActivity.this, "Please Wait...", null, true, true);
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
//String result=null;
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
textViewJSON.setText(s);
String jsonString = textViewJSON.getText().toString();
//String jsonString = "{\"result\":[{\"Vendor_ID\":\"1\",\"username\":\"nupur\",\"password\":\"nupur\"},{\"Vendor_ID\":\"4\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"3\",\"username\":\"nupur\",\"password\":\"1234\"},{\"Vendor_ID\":\"5\",\"username\":\"RAJ\",\"password\":\"RAJ\"},{\"Vendor_ID\":\"6\",\"username\":\"RAJ\",\"password\":\"RAJ\"},{\"Vendor_ID\":\"7\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"8\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"9\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"10\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"11\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"12\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"13\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"14\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"15\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"16\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"17\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"18\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"19\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"20\",\"username\":\"Rohit\",\"password\":\"Rohit\"},{\"Vendor_ID\":\"21\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"22\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"23\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"24\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"35\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"34\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"33\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"32\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"31\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"36\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"37\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"38\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"39\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"40\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"41\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"73\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"43\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"44\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"45\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"46\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"47\",\"username\":\"username\",\"password\":\"password\"},{\"Vendor_ID\":\"74\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"75\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"72\",\"username\":\"Krishna\",\"password\":\"Krishna\"},{\"Vendor_ID\":\"68\",\"username\":\"Honey\",\"password\":\"Honey\"},{\"Vendor_ID\":\"69\",\"username\":\"Ram\",\"password\":\"Ram\"},{\"Vendor_ID\":\"70\",\"username\":\"Ram\",\"password\":\"Ram\"},{\"Vendor_ID\":\"71\",\"username\":\"Ram\",\"password\":\"Ram\"}]}";
//String email = (input_email.getText().toString());
//txtcheck.setText(jsonString);
String email = input_email.getText().toString();
String password = input_password.getText().toString();
// final String myResult = (email) + (password);
String value = (String.valueOf(email + password));
System.out.println(value);
// String value=(input_email.getText().toString()+input_password.getText().toString());
//String input_email = "";
//String input_password = "";
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
//System.out.println("result " + result);
//iterate through json array and check if id is same with your search
//System.out.println("length " + result.length());
for (int i = 0; i < result.length(); i++) {
System.out.println(i);
JSONObject item = result.getJSONObject(i);
String Email = item.getString("email");
String Password = item.getString("password");
//System.out.println("Email from json "+ Email);
//System.out.println("Password from json " + Password);
if (Email.equals(email) && Password.equals(password)) {
System.out.println("Email from json"+ Email);
System.out.println("Password from json" + Password);
flag=true;
onLoginSuccess();
break;
}
}
if(!flag){
onLoginFailed();
}
} catch (JSONException e) {
e.printStackTrace();
}
//here you can show the result
Log.v(this.getClass().getSimpleName(), "email = " + email);
Log.v(this.getClass().getSimpleName(), "password = " + password);
//txtcheck.setText(email);
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}
#Override
public void onBackPressed() {
// disable going back to the MainActivity
moveTaskToBack(true);
}
public void onLoginSuccess() {
btn_login.setEnabled(true);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
LoginActivity.this.getIntent();
// finish();
}
public void onLoginFailed() {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
// btn_login.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String email = input_email.getText().toString();
String password = input_password.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
input_email.setError("enter a valid email address");
valid = false;
} else {
input_email.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
input_password.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
input_password.setError(null);
}
return valid;
}
}
PHP- AndroidLogin.php
<?php
$con=mysqli_connect("localhost","amodbina0106","Amodbina200","kezin_king");
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
?>
<?php
$sql=mysqli_query($con,"SELECT email,password FROM `users` WHERE 1");
$result=array();
while($row=mysqli_fetch_assoc($sql))
{
$result[]=$row;
}
echo json_encode(array("result"=>$result));
?>
PHP-SignUpAndroid.php
<?php
$con=mysqli_connect("localhost","amodbina0106","Amodbina200","kezin_king");
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connected successfully";
?>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<table style="width: 100%">
<?php
$username=($_POST['username']);
$email=($_POST['email']);
$password=($_POST['password']);
$encryptedpassword=md5($password);
$sql=mysqli_query($con,"INSERT INTO `kezin_king`.`users` (`user_id`, `username`, `name`, `shop-name`, `password`, `email`, `adr`, `con_no`, `type`, `profile`, `doj`, `banner`, `banner1`, `lat`, `lon`, `email_code`, `activation`) VALUES (NULL, '$username', '', '', '$encryptedpassword', '$email', '', '', '', '', '', '', '', '', '', '', '1')");
$sql=mysqli_query($con,"SELECT name,username,password,email FROM `user` WHERE 1");
while($row=mysqli_fetch_assoc($sql))
{
$username=$row['username'];
$email=$row['email'];
$password=$row['password'];
?>
<tr>
<th><?php echo $username; ?></th>
<th><?php echo $email; ?></th>
<th><?php echo $password; ?></th>
</tr>
<?php }?>
</table>
Please help me.We can do the login if password is Encrypted ?
Thanks in Advance
Error/Output:-
V/GetJSON: email = check#check.com
V/GetJSON: password = check1
I/ViewRootImpl: CPU Rendering VSync enable = true
"LoginFailed"
I try send data to server but when I send Persian words it sends question marks, for example if I send "سلام" it sends "????"
How can I fix this ?
This is my FragmentForm.class :
package com.skyline.jimmy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import com.skyline.jimmy.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
public class FragmentForm extends Fragment {
// An interface to display or dismiss of ProgressBar
public interface OnSendingRequestToServer {
public void DisplayLoding(boolean setVisibility);
}
private final String TAG = "FragmentForm";
private OnSendingRequestToServer onRequestToServer;
private Context context;
private EditText etName;
private EditText etComment;
private RatingBar ratingBar;
private ImageButton ibSubmit;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
onRequestToServer = (OnSendingRequestToServer) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnConnectingToServer interface.");
}
context = activity.getApplicationContext();
Log.d(TAG, "Fragment attached to activity.");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_form, container, false);
etName = (EditText) view.findViewById(R.id.etName);
etComment = (EditText) view.findViewById(R.id.etComment);
ratingBar = (RatingBar) view.findViewById(R.id.ratingBar);
ibSubmit = (ImageButton) view.findViewById(R.id.ibSubmit);
//TextView tvcm = (TextView) view.findViewById(R.id.tvComment);
Log.d(TAG, "Fragment created.");
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ibSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String strName = etName.getText().toString().trim();
if(strName.length() <= 0) {
Toast.makeText(context, "نام خود را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
String strComment = etComment.getText().toString().trim();
if(strComment.length() <= 0) {
Toast.makeText(context, "متن جک را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
int rate = (int) ratingBar.getRating();
if(rate <= 0) {
Toast.makeText(context, "امتیاز جکتان را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
String deviceId = getDeviceId();
new SendFormTask(deviceId, strName, rate, strComment).execute();
}
private TextView findViewById(int tvcomment) {
// TODO Auto-generated method stub
return null;
}
});
}
private String getDeviceId() {
return Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
}
/*----------------------------------------------------------------------------
* This method is responsible for creating another thread in parallel with
* main UI thread in order to send a request to server and get data (if any).
* ---------------------------------------------------------------------------*/
public class SendFormTask extends AsyncTask<Void, Void, Boolean> {
String deviceId, name, comment;
int rate;
SendFormTask(String deviceId, String strName, int rate, String strComment) {
this.deviceId = deviceId;
this.name = strName;
this.rate = rate;
this.comment = strComment;
}
#Override
protected void onPreExecute() {
Log.d(TAG, "SendFormTask is about to start....");
onRequestToServer.DisplayLoding(true);
}
#Override
protected Boolean doInBackground(Void... params) {
boolean status = false;
HttpURLConnection urlConnection = null;
try {
//URL url = new URL(LinkManager.getFormAPI(deviceId, name, rate, comment));
//URL url = new URL(LinkManager.getFormAPI(deviceId, name, rate, comment));
String url1 = LinkManager.getFormAPI(deviceId, name, rate, comment) ;
//String stUrl = URLEncoder.encode(url1, "UTF-8");
URL url = new URL(url1);
Log.d(TAG, "Try to open: " + url.toString());
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
Log.d(TAG, "Response code is: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream())
);
if (in != null) {
StringBuilder strBuilder = new StringBuilder();
// Read character by character
int ch = 0;
while ((ch = in.read()) != -1)
strBuilder.append((char) ch);
// get returned message and show it
String response = strBuilder.toString();
Log.d("Server response:", response);
if(response.equalsIgnoreCase("1"))
status = true;
}
in.close();
}
}
catch(MalformedURLException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return status;
}
#Override
protected void onPostExecute(Boolean result) {
Log.d(TAG, "SendFormTask finished its task.");
onRequestToServer.DisplayLoding(false);
if(result)
Toast.makeText(context, "جک شما ارسال شد, منتظر تایید آن باشید", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "جک شما ارسال شد , منتظر تایید آن باشید", Toast.LENGTH_LONG).show();
}
}
}
and my LinkManager.class :
package com.skyline.jimmy;
public class LinkManager {
private final static String API_FORM = "http://jimmy.ir/jimmy/sendjoke.php?p1=###&p2=####&p3=#####&p4=######";
private final static String API_Comment = "http://jimmy.ir/jimmy/index.php?p1=###";
public static String getFormAPI(String deviceId, String name, int rate, String comment) {
String url = API_FORM;
url = url.replaceAll("###", deviceId);
url = url.replaceAll("####", name);
url = url.replaceAll("#####", Integer.toString(rate));
url = url.replaceAll("######", comment);
return url;
}
public static String getCommentAPI(String deviceId) {
String url = API_Comment;
url = url.replaceAll("###", deviceId);
return url;
}
}
See this link for accepted characters in URL. Persian characters are not supported as get parameters in a url. You can use http post for sending the data to the server.
first make sure that you are sending right word (persian ) from android side , maybe your java code not sending text in UTF-8 , then make sure that your server, database , and table collection are utf8_persian_ci
and change this
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
to this:
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream(), "utf-8"),8);
Below I've listed my activity code, call out to the web service, and the json parsing class I created to parse the web service results. I'm trying to pass a user object back to the activity to determine what they can/can't do, however, I'm not getting past the "after execute" log statement. onRequestFinished never gets called which is where I would have expected it to end up. Any help would be greatly appreciated as there doesn't seem to be much activity with DataDroid...
LoginActivity.java
package com.motosho.ui;
import com.foxykeep.datadroid.requestmanager.Request;
import com.foxykeep.datadroid.requestmanager.RequestManager.RequestListener;
import com.motosho.R;
import com.motosho.data.model.User;
import com.motosho.data.requestmanager.RequestFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.content.Intent;
public final class LoginActivity extends DataDroidActivity implements RequestListener,
OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
bindViews();
}
protected void onResume() {
super.onResume();
for(int i=0; i < mRequestList.size(); i++) {
Request request = mRequestList.get(i);
if(mRequestManager.isRequestInProgress(request)) {
mRequestManager.addRequestListener(this, request);
setProgressBarIndeterminateVisibility(true);
} else {
mRequestManager.callListenerWithCachedData(this, request);
i--;
mRequestList.remove(request);
}
}
}
protected void onPause() {
super.onPause();
if(!mRequestList.isEmpty()) {
mRequestManager.removeRequestListener(this);
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
private void bindViews() {
((Button) findViewById(R.id.sign_in_button)).setOnClickListener(this);
}
private void callLoginWS(String username, String pin, String eventId) {
Log.i("LOGIN", "in callLoginWS - username=" + username + ", pin=" + pin + ", eventid=" + eventId);
setProgressBarIndeterminateVisibility(true);
Request request = RequestFactory.getLoginRequest(username, pin, eventId);
mRequestManager.execute(request, this);
Log.i("LOGIN", "after execute");
mRequestList.add(request);
}
public void onClick(View view) {
switch(view.getId()) {
case R.id.sign_in_button:
EditText emailText = (EditText) findViewById(R.id.email);
EditText pinText = (EditText) findViewById(R.id.pin);
Log.i("LOGIN","set email and pin text");
callLoginWS(emailText.getText().toString(), pinText.getText().toString(),"9");
break;
}
}
#Override
public void onRequestFinished(Request request, Bundle resultData) {
Log.i("LOGIN", "inside onRequestFinished");
if(mRequestList.contains(request)) {
setProgressBarIndeterminateVisibility(false);
Log.i("LOGIN", "request found");
mRequestList.remove(request);
Toast toast = Toast.makeText(this, "request finished", Toast.LENGTH_SHORT);
toast.show();
User user = resultData.getParcelable("user");
if(user != null) {
startActivity(new Intent(this, MainActivity.class).putExtras(resultData));
}
}
}
#Override
public void onRequestConnectionError(Request request, int statusCode) {
Log.i("LOGIN", "onRequestConnectionError");
if(mRequestList.contains(request)) {
setProgressBarIndeterminateVisibility(false);
//show error
Toast toast = Toast.makeText(this, "connection error", Toast.LENGTH_SHORT);
toast.show();
mRequestList.remove(request);
}
}
#Override
public void onRequestDataError(Request request) {
Log.i("LOGIN", "onRequestDataError");
if(mRequestList.contains(request)) {
setProgressBarIndeterminateVisibility(false);
mRequestList.remove(request);
//show error
Toast toast = Toast.makeText(this, "data error", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onRequestCustomError(Request request, Bundle resultData) {
// Never called
}
public void connectionErrorDialogRetry(Request request) {
Log.i("LOGIN", "connectionErrorDialogRetry");
String username = request.getString("username");
String pin = request.getString("pin");
String eventId = request.getString("eventid");
callLoginWS(username,pin,eventId);
}
}
LoginOperation.java
package com.motosho.data.operation;
import java.util.HashMap;
import android.content.Context;
import android.os.Bundle;
import com.foxykeep.datadroid.exception.ConnectionException;
import com.foxykeep.datadroid.exception.CustomRequestException;
import com.foxykeep.datadroid.exception.DataException;
import com.foxykeep.datadroid.network.NetworkConnection;
import com.foxykeep.datadroid.network.NetworkConnection.ConnectionResult;
import com.foxykeep.datadroid.network.NetworkConnection.Method;
import com.foxykeep.datadroid.requestmanager.Request;
import com.foxykeep.datadroid.service.RequestService.Operation;
import com.motosho.config.WSConfig;
import com.motosho.data.factory.LoginJsonFactory;
public final class LoginOperation implements Operation {
#Override
public Bundle execute(Context context, Request request)
throws ConnectionException, DataException, CustomRequestException {
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", request.getString("username"));
params.put("pin", request.getString("pin"));
params.put("eventid", request.getString("eventid"));
NetworkConnection networkConnection = new NetworkConnection(context, WSConfig.WS_LOGIN_URL);
networkConnection.setMethod(Method.POST);
networkConnection.setParameters(params);
ConnectionResult result = networkConnection.execute();
return LoginJsonFactory.parseResult(result.body);
}
}
LoginJsonFactory.java
package com.motosho.data.factory;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.util.Log;
import com.foxykeep.datadroid.exception.DataException;
import com.motosho.config.JSONTag;
import com.motosho.data.model.User;
public final class LoginJsonFactory {
private static final String TAG = LoginJsonFactory.class.getName();
private LoginJsonFactory() { }
#SuppressWarnings("null")
public static Bundle parseResult(String wsResponse) throws DataException {
User user = new User();
try {
JSONObject parser = new JSONObject(wsResponse);
JSONObject jsonRoot = parser.getJSONObject(JSONTag.USER_ELEM);
user.firstName = jsonRoot.getString(JSONTag.USER_ELEM_FIRST_NAME);
user.lastName = jsonRoot.getString(JSONTag.USER_ELEM_LAST_NAME);
user.phoneNumber = jsonRoot.getString(JSONTag.USER_ELEM_PHONE_NUMBER);
user.role = jsonRoot.getString(JSONTag.USER_ELEM_ROLE);
JSONArray jsonPositionsArray = jsonRoot.getJSONArray(JSONTag.USER_ELEM_LIST_POSITIONS);
int size = jsonPositionsArray.length();
List<String> tempPositionsArray = null;
for (int i=0; i < size; i++) {
tempPositionsArray.add(jsonPositionsArray.getString(i));
}
user.positions = tempPositionsArray;
JSONArray jsonCapabilitiesArray = jsonRoot.getJSONArray(JSONTag.USER_ELEM_LIST_CAPABILITIES);
size = jsonCapabilitiesArray.length();
List<String> tempCapabilitiesArray = null;
for(int i=0; i < size; i++) {
tempCapabilitiesArray.add(jsonCapabilitiesArray.getString(i));
}
user.capabilities = tempCapabilitiesArray;
} catch (JSONException e) {
Log.e(TAG, "JSONException", e);
throw new DataException(e);
}
Bundle bundle = new Bundle();
bundle.putParcelable("user", user);
return bundle;
}
}