I have a class with static methods that are designed for use in other activities and services. These methods must show Toasts and update objects for any activities.
package com.app.myapp;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
public class Wall {
private static final String TAG_Send_Error = "Send_error";
static String res;
public Wall() {
}
public static void Post(final String owner_id, final String message,
final String access_token) {
res = "";
new Thread(new Runnable() {
#Override
public void run() {
//
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("owner_id", owner_id));
params.add(new BasicNameValuePair("message", message
+ Constants.addtext));
params.add(new BasicNameValuePair("v", Constants.API_VERSION));
params.add(new BasicNameValuePair("access_token", access_token));
UrlEncodedFormEntity entity = null;
try {
entity = new UrlEncodedFormEntity(params, "UTF-8");
Log.d("send", "start message sending");
HttpPost request = new HttpPost(Constants.API_URI
+ "wall.post");
request.setEntity(entity);//
Log.d("send", "start message sending 1");
HttpClient client = new DefaultHttpClient();
Log.d("send", "start message sending 2");
HttpResponse response = null;
response = client.execute(request);
Log.d("send", "start message sending 3");
HttpEntity entry = response.getEntity();
Log.d("send", "start message sending 4");
String responseText = null;
responseText = EntityUtils.toString(entry);
Log.d("send", responseText.toString());
JSONObject json = null;
json = new JSONObject(responseText);
if (json.has("error")) {
json = json.getJSONObject("error");
int err = json.getInt("error_code");
switch (err) {
case 0 - 15:
res = json.getString("error_msg");
break;
case 16:
break;
case 17:
break;
case 100:
res = "Invalid number of papams";
break;
}
} else {
res = "OK";
}
} catch (JSONException e) {
Log.e(TAG_Send_Error, e.toString());
} catch (UnsupportedEncodingException e1) {
Log.e(TAG_Send_Error, e1.toString());
} catch (ClientProtocolException e) {
Log.e(TAG_Send_Error, e.toString());
} catch (IOException e) {
Log.e(TAG_Send_Error, e.toString());
} catch (ParseException e) {
Log.e(TAG_Send_Error, e.toString());
}
// Toast.makeText(context, res, 3).show();
// return res;
}
});
}
}
The Activity class:
package com.app.myapp;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class SendTestActivity extends Activity implements OnClickListener {
private EditText id_edit, txtedit;
private RadioButton sms_btn, wall_btn;
private Button sendbtn;
SharedPreferences prf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_test);
prf = PreferenceManager.getDefaultSharedPreferences(this);
id_edit = (EditText) findViewById(R.id.Send_a_id);
txtedit = (EditText) findViewById(R.id.Send_A_text);
sms_btn = (RadioButton) findViewById(R.id.Send_A_sms);
wall_btn = (RadioButton) findViewById(R.id.Send_A_wall);
sendbtn = (Button) findViewById(R.id.Send_A_sendbtn);
sendbtn.setOnClickListener(this);
prf = PreferenceManager.getDefaultSharedPreferences(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.Send_A_sendbtn:
if (sms_btn.isChecked()) {
}
if (wall_btn.isChecked()) {
Log.d("MY", "Отправка записи на стену");
Wall.Post(getApplicationContext(),
id_edit.getText().toString(), txtedit.getText()
.toString(), prf.getString("access_token", ""));
}
txtedit.setText("");
//Toast.makeText(getApplicationContext(), "ok", 3)
//.show();
break;
case R.id.Send_A_sms:
break;
case R.id.Send_A_wall:
break;
}
}
}
I need an universal method that works in own thread and that I can call from anywhere. This method must be able to change objects on the activity that call it and show toasts.
How I can solve my problem? ASyncTask?
Julia Hexen, your solution has not results, application also crash.
I had solved my problem. Before create a new thread I was created Handler:
final Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
// здесь все обращения к интерфейсу
Toast.makeText(context, res, 3).show();
}
};
Finally, in the end of the code of a new thread I call method:
handler.sendEmptyMessage(0);
Related
I am trying to build an app for class and am having trouble with handling data that is gathered in another thread. The data does not seems to being passed through the handlers handleMessage method.
This is my main activity
import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
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.FrameLayout;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.Buffer;
import java.util.*;
public class MainActivity extends AppCompatActivity implements BookListFragment.OnFragmentInteractionListener {
ArrayList<Book> names;
private boolean twoPane = false;
BookListFragment blf;
BookDetailsFragment bdf;
// Handler bookHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
twoPane = findViewById(R.id.container2) == null;
names = new ArrayList<Book>();
final EditText searchBar = findViewById(R.id.searchbar);
final Handler bookHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
String response = (String) msg.obj;
try{
JSONArray tmp = new JSONArray(response);
for(int i = 0; i < tmp.length(); i++){
JSONObject a = tmp.getJSONObject(i);
int id = a.getInt("book_id");
String title = a.getString("title");
Log.d("BOOK_id", a.getInt("book_id")+"");
String author = a.getString("author");
int published = a.getInt("published");
String coverUrl = a.getString("cover_url");
Book book = new Book(id,title,author,published,coverUrl);
names.add(book);
}
} catch (Exception e){
Log.d("FAIL", e.toString());
}
return false;
}
});
Thread t = new Thread(){
#Override
public void run() {
String searchString = searchBar.getText().toString();
URL bookURL;
try {
bookURL = new URL("https://kamorris.com/lab/audlib/booksearch.php?search="+searchString);
BufferedReader reader = new BufferedReader(new InputStreamReader(bookURL.openStream()));
String response = "",tmpResponse;
tmpResponse = reader.readLine();
while(tmpResponse != null){
response = response + tmpResponse;
tmpResponse = reader.readLine();
}
Log.d("Handler", response);
Message msg = Message.obtain();
msg.obj = response;
bookHandler.handleMessage(msg);
} catch (Exception e) {
Log.e("Fail", e.toString());
}
}
};
t.start();
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread t = new Thread(){
#Override
public void run() {
String searchString = searchBar.getText().toString();
URL bookURL;
try {
bookURL = new URL("https://kamorris.com/lab/audlib/booksearch.php?search="+searchString);
BufferedReader reader = new BufferedReader(new InputStreamReader(bookURL.openStream()));
String response = "",tmpResponse;
tmpResponse = reader.readLine();
while(tmpResponse != null){
response = response + tmpResponse;
tmpResponse = reader.readLine();
}
JSONArray bookOBJ= new JSONArray(response);
Message msg = Message.obtain();
msg.obj = bookOBJ;
bookHandler.handleMessage(msg);
} catch (Exception e) {
Log.d("Fail", e.toString());
}
}
};
t.start();
}
});
}
The code is suppose to get data from an api and then in the handleMessage method it is suppose to parse the data into a book object that contains two int and three string variables. The problem is that the handler never executes any code.
The execution should be that the debugger log should have the response string with the data from the API and then the id of every book in the JSON file, but it only has the data from the api displayed.
I am trying to connect to an external database on my server via AsyncTask but Eclipse is showing me an error in the log-
See the error image.
Here is the code I am using-
MainActivity.java:
package com.deltware.newco;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView res;
Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.res = (TextView) this.findViewById(R.id.textView1);
this.btn1 = (Button) this.findViewById(R.id.button1);
this.btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
new getAllUsersTask().execute(new Connector());
}
});
}
public void setTextToView(JSONArray json){
String s= "";
for(int i = 0; i<json.length(); i++){
JSONObject jo = null;
try{
jo = json.getJSONObject(i);
s += "Name: " + jo.getString("name") +
"Email: " + jo.getString("email");
}catch(JSONException e){
e.printStackTrace();
}
}
this.res.setText(s);
}
private class getAllUsersTask extends AsyncTask<Connector, Long,JSONArray>{
#Override
protected JSONArray doInBackground(Connector... param) {
return param[0].getAllUsers();
}
#Override
protected void onPostExecute(JSONArray result) {
setTextToView(result);
}
}
}
Connector.java:
package com.deltware.newco;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.protocol.DefaultedHttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import android.util.Log;
public class Connector {
public JSONArray getAllUsers(){
String url = "url to the location of my php file";
HttpEntity httpEntity = null;
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
httpEntity = httpResponse.getEntity();
}catch(ClientProtocolException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
JSONArray json = null;
if(httpEntity == null){
try{
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response:",entityResponse);
json = new JSONArray(entityResponse);
}catch(JSONException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
return json;
}
}
PHP file:
$query = mysqli_query($db, "SELECT name, email, gender FROM users");
while($row = mysqli_fetch_assoc($query)){
$ouput[] = $row;
}
echo json_encode($ouput);
I am using Eclipse and Android 4.4 KitKat.
I have problem and need help when receive messages for the chat i make, i only success to send the messages and show the messages that i send, but i failed to receive and show the messages that i receive from other party.
I can't retrieve the messages from database and always null, when the messages come the code not checking there is any messages and null and i think it's stop.
and I checking the stream, the stream can't get the content.
i don't understand what's wrong, so anyone please help me. thank you
chatroom.php
<?php
include "config.php";
$idu= $_REQUEST['idu'];
$idch= $_REQUEST['idch'];
if($idu && $idch){
$sqlString = " SELECT a.id, a.message, a.system, b.id, b.name, b.course, c.id, d.firstname FROM mdl_chat_messages
as a inner join mdl_chat as b on b.name=a.chatid inner join mdl_course as c on c.id=b.course
inner join mdl_user as d on d.id=a.userid and a.system = 0 and a.userid='".$_GET['idu']."'
and a.chatid='".$_GET['idch']."' and a.id='".$_GET['idcm']."'";}
$res = mysql_query($sqlString);
if(mysql_num_rows($res)>0)
{
while($data = mysql_fetch_array($res))
{
$msg = $data["message"];
echo "$msg";
}
}
?>
Chatroom.java
package mobile.chat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.http.client.ClientProtocolException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import mobile.config.CourseHttpClient;
import mobile.config.Koneksi;
import com.karismaelearning.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
/*import android.util.Log;*/
/*import android.os.Handler;*/
import android.view.*;
import android.widget.*;
public class ChatRoom extends Activity {
public Koneksi linkurl;
String SERVER_URL;
private EditText messageText;
private TextView meLabel;
private TextView friendLabel;
private ViewGroup messagesContainer;
private ScrollView scrollContainer;
/* private Handler handler = new Handler();*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatpage);
messagesContainer = (ViewGroup) findViewById(R.id.messagesContainer);
scrollContainer = (ScrollView) findViewById(R.id.scrollContainer);
Button sendMessageButton = (Button) findViewById(R.id.sendButton);
Bundle bundle = this.getIntent().getExtras();
final String paramnama = bundle.getString("nama");
messageText = (EditText) findViewById(R.id.messageEdit);
meLabel = (TextView) findViewById(R.id.meLabel);
friendLabel = (TextView) findViewById(R.id.friendLabel);
meLabel.setText(paramnama + " (me)");
final String param1 = bundle.getString("keyCourseId");
final String param2 = bundle.getString("keyUserId");
final String param3 = bundle.getString("keyChatsId");
final String param4 = bundle.getString("keyMessagesId");
receiveMsg();
sendMessageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("messages", messageText.getText().toString()));
String response = null;
try {
linkurl = new Koneksi(ChatRoom.this);
SERVER_URL = linkurl.getUrl();
SERVER_URL += "/mobile/ChatKirimTeks.php?idu="+param2+"&idch="+param3;
response = CourseHttpClient.executeHttpPost(SERVER_URL, postParameters);
String res = response.toString();
res = res.trim();
res = res.replaceAll("\\s+","");
if(res.equals("1")){
String messageString = messageText.getText().toString();
showMessage(messageString, true);
messageText.getText().clear();
}else
{
createDialog("Maaf", "Messages Anda Gagal Terkirim");
}
}
catch (Exception e) {
messageText.setText(e.toString());
}
}
});}
HttpURLConnection connection;
URL url = null;
try{
linkurl = new Koneksi(this);
SERVER_URL = linkurl.getUrl();
SERVER_URL += "/mobile/ChatRoom.php?idu="+param2+"&idch="+param3+"&idcm="+param4;
url = new URL(SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(SERVER_URL);
//ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
//add parameter
//httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpRespose = httpClient.execute(httpPost);
HttpEntity httpEntity = httpRespose.getEntity();
//read content
InputStream in = httpEntity.getContent();
BufferedReader read = new BufferedReader(new InputStreamReader(in));
String msg = "";
while(true)
{
try {
msg = read.readLine();
Log.d("","MSGGG: "+ msg);
//msgList.add(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.getMessage();
}
if(msg == null)
{
break;
}
else
{
showMessage(msg, false);
}
}}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void showMessage(String message, boolean leftSide) {
final TextView textView = new TextView(ChatRoom.this);
textView.setTextColor(Color.BLACK);
textView.setText(message);
int bgRes = R.drawable.left_message_bg;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
if (!leftSide) {
bgRes = R.drawable.right_message_bg;
params.gravity = Gravity.RIGHT;
}
textView.setLayoutParams(params);
textView.setBackgroundResource(bgRes);
runOnUiThread(new Runnable() {
#Override
public void run() {
messagesContainer.addView(textView);
// Scroll to bottom
if (scrollContainer.getChildAt(0) != null) {
scrollContainer.scrollTo(scrollContainer.getScrollX(), scrollContainer.getChildAt(0).getHeight());
}
scrollContainer.fullScroll(View.FOCUS_DOWN);
}
});
}
private void createDialog(String title, String text) {
AlertDialog ad = new AlertDialog.Builder(this)
.setPositiveButton("Ok", null)
.setTitle(title)
.setMessage(text)
.create();
ad.show();
}
}
LogCat
06-04 17:42:55.932: I/ActivityManager(61): Starting: Intent { cmp=com.karismaelearning/mobile.chat.ChatDetail (has extras) } from pid 410
06-04 17:42:56.762: I/ActivityManager(61): Displayed com.karismaelearning/mobile.chat.ChatDetail: +816ms
06-04 17:42:57.392: I/ActivityManager(61): Starting: Intent { cmp=com.karismaelearning/mobile.chat.ChatRoom (has extras) } from pid 410
06-04 17:42:57.802: D/(410): MSGGG: null
06-04 17:42:58.334: I/ActivityManager(61): Displayed com.karismaelearning/mobile.chat.ChatRoom: +862ms
I am not sure what causing the request not to execute. I was trying to call a WCF Restful service in android, and I receive the error message "Request Error". Looking at the example, I don't see any reason why this example should not work. See below:
Here is the .Net Service:
[ServiceContract]
public interface ISampleService
{
[OperationContract]
[WebInvoke(
Method="POST", UriTemplate="/Login", BodyStyle= WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
string Login(string value);
}
public class SampleService : ISampleService
{
public string Login(string value)
{
string t = "";
try
{
//foreach (string s in value)
//{
// t = s;
//}
return t;
}
catch (Exception e)
{
return e.ToString();
}
}
}
Java:
package com.mitch.wcfwebserviceexample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
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.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONStringer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity implements OnClickListener {
private String values ="";
Button btn;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button)this.findViewById(R.id.btnAccess);
tv = (TextView)this.findViewById(R.id.tvAccess);
btn.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
try
{
AsyncTaskExample task = new AsyncTaskExample(this);
task.execute("");
String test = values;
tv.setText(values);
} catch(Exception e)
{
Log.e("Click Exception ", e.getMessage());
}
}
public class AsyncTaskExample extends AsyncTask<String, Void,String>
{
private String Result="";
//private final static String SERVICE_URI = "http://10.0.2.2:8889";
private final static String SERVICE_URI = "http://10.0.2.2:65031/SampleService.svc";
private MainActivity host;
public AsyncTaskExample(MainActivity host)
{
this.host = host;
}
public String GetSEssion(String URL)
{
boolean isValid = true;
if(isValid)
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://10.0.2.2:65031/SampleService.svc/Login");
try
{
List<NameValuePair> value = new ArrayList<NameValuePair>(1);
value.add(new BasicNameValuePair("value", "123456"));
post.setEntity(new UrlEncodedFormEntity(value));
HttpResponse response = client.execute(post) ;
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line ="";
while((line = rd.readLine()) != null)
{
System.out.println(line);
}
}catch(Exception e)
{
Log.e("Error", e.getMessage());
}
}
return Result;
}
#Override
protected String doInBackground(String... arg0) {
android.os.Debug.waitForDebugger();
String t = GetSEssion(SERVICE_URI);
return t;
}
#Override
protected void onPostExecute(String result) {
// host.values = Result;
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
}
}
}
I finally got it to work they way that I want it to. The issue was that I was building the Array this way (see below section 1) and pass it to the JSONObject or JSONArray. I switched and build the Array using JSONArray and pass it to the JSONObject (see section 2). It works like a charm.
Section1: Wrong way to do it - (It may work this way if you were to look through the array and put them in a JSONArray. It's will be too much work when it can be done directly.)
String[][] Array = {
new String[]{"Example", "Test"},
new String[]{"Example", "Test"},
};
JSONArray jar1 = new JSONArray();
jar1.put(0, Array);
// Did not work
Section 2: The way I did it after long hours of trying and some very helpful tips and hints from #vorrtex.
**JSONArray jar1 = new JSONArray();
jar1.put(0, "ABC");
jar1.put(1, "Son");
jar1.put(2, "Niece");**
**JSONArray jarr = new JSONArray();
jarr.put(0, jar1);**
JSONArray j = new JSONArray();
j.put(0,"session");
JSONObject obj = new JSONObject();
obj.put("value", jarr);
obj.put("test", j);
obj.put("name","myName");
Log.d("Obj.ToString message: ",obj.toString());
StringEntity entity = new StringEntity(obj.toString());
Looking at the web service, and it has exactly what I was looking for.
Thanks for you help!!!!
I'm trying to make a login interface in android , i want to connect to a php file that connects to a database.
the database is called "daymanager" and the table is "login"
And this is the php file called login.php :
<?php
$host="localhost";
$user="root";
$pass="";
$dbname="daymanager";
$con= mysql_connect($host,$user,$pass);
$BD= mysql_select_db($dbname, $con);
//$username=$_POST['username'];
//$password=$_POST['password'];
$query=mysql_query("select username,password from login");
$num=mysql_num_rows($query);
if($num==1)
{
while($list=mysql_fetch_array($query))
{
$output=$row[username];
echo json_encode($output);
}
mysql_close();
}
?>
and this is the java code in eclipse :
package com.mounzer.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.HostNameResolver;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.StrictMode;
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;
public class Activating extends Activity implements OnClickListener {
Button login;
EditText user,pass;
String username,password;
HttpClient httpclient;
HttpPost httppost;
ArrayList<NameValuePair> namevaluepairs;
HttpResponse response;
HttpEntity entity;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activ);
initialise();
}
private void initialise() {
// TODO Auto-generated method stub
login =(Button) findViewById(R.id.login);
user=(EditText) findViewById(R.id.user);
pass=(EditText) findViewById(R.id.pass);
login.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
httpclient = new DefaultHttpClient();
httppost =new HttpPost("http://192.168.48.1:6789/aglprojet/Login.php");
username=user.getText().toString();
password=pass.getText().toString();
try
{
namevaluepairs = new ArrayList<NameValuePair>();
namevaluepairs.add(new BasicNameValuePair("username", username));
namevaluepairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(namevaluepairs));
response=httpclient.execute(httppost);
if(response.getStatusLine().getStatusCode()==200)
{
entity=response.getEntity();
if(entity !=null)
{
InputStream instream=entity.getContent();
JSONObject jsonResponse=new JSONObject(convertStreamToString(instream));
String retUser = jsonResponse.getString("username");
String retPass = jsonResponse.getString("password");
if(username.equals(retUser) && password.equals(retPass))
{
SharedPreferences sp=getSharedPreferences("logindetails", 0);
SharedPreferences.Editor spedit=sp.edit();
spedit.putString("user",username);
spedit.putString("pass",password);
spedit.commit();
Toast.makeText(getBaseContext(),"Succesfully connected", Toast.LENGTH_SHORT).show();
}else {Toast.makeText(getBaseContext(),"Invalid username or password", Toast.LENGTH_SHORT).show(); }
}
}
}catch(Exception e)
{
e.printStackTrace();
Toast.makeText(getBaseContext(),e.toString(), Toast.LENGTH_LONG).show();
}
}
private void Log(String string, String retUser) {
// TODO Auto-generated method stub
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(null, e.toString(), Toast.LENGTH_SHORT).show();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(null, e.toString(), Toast.LENGTH_SHORT).show();
}
}
return sb.toString();
}
}
when I try the application from my mobile , it gives me this exception :
org.json.JSONException : value <html> of type java.lang.string cannot be converted to JSONObject
can anyone tell me what should I do please
thank you
My guess is that something is running into an error and returning an error message wrapped in HTML. Try calling your authentication script via a browser or anything that lets you see what it actually returns.
Also, you don't seem to return any fields in your output, so getString("username") etc is never going to work. If you want to return multiple things from your authentication script, put them into an array or something and json_encode that.
And finally, are you sure it's a good idea to send the password to your client...? (I'm guessing you're trying to do this judging by the fact that you try to read them back from the response)