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.
Related
i am just a beginner in developing android applications, i wanted to connect my application to a server so i could get data from MySQL. so i tried to make login part first but i have some problems. my code doesn't work for reading JSON.
my codes are as below:
LoginActivity(MainActivity) :
package ir.naserpour.sportclub;
import android.content.Context;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class LoginActivity extends AppCompatActivity {
String link;
String response;
//get values
String username,password;
#Override
protected void attachBaseContext (Context newBase){
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//define things
TextView menu = (TextView) findViewById(R.id.menu);
final EditText login_username = (EditText) findViewById(R.id.login_username);
final EditText login_password = (EditText) findViewById(R.id.login_password);
Button login_login = (Button) findViewById(R.id.login_login);
Button login_register = (Button)findViewById(R.id.login_register);
CheckBox rememberme = (CheckBox)findViewById(R.id.login_remeberme);
//set icon type face
Typeface fonticon = Typeface.createFromAsset(getAssets(), "fonts/icon.ttf");
menu.setTypeface(fonticon);
login_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
username = login_username.getText().toString();
password = login_password.getText().toString();
//check values
if (username.length() <1 || password.length() < 1) {
Toast.makeText(getApplicationContext(), "fields cannot be empty", Toast.LENGTH_SHORT).show();
} else {
//generate link
link = "http://localhost:8080/login.php?username="+username+"&password="+password;
login();
if(response=="true"){
Toast.makeText(getApplicationContext(), "true", Toast.LENGTH_SHORT).show();
}else if(response=="false"){
Toast.makeText(getApplicationContext(), "false", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "response", Toast.LENGTH_SHORT).show();
}
}
}
});
}
#Override
protected void onPause () {
super.onPause();
finish();
}
public String login() {
new JSONParse().execute();
return response;
}
public class JSONParse extends AsyncTask<String, String, JSONObject> {
#Override
public void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(),"getting data ...",Toast.LENGTH_SHORT).show();
}
#Override
public JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(link);
return json;
}
#Override
public void onPostExecute(JSONObject json) {
try {
JSONArray result = json.getJSONArray("result");
JSONObject c = result.getJSONObject(0);
try {
String res = new String(c.getString("response").getBytes("ISO-8859-1"), "UTF-8");
response = res;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser.java:
package ir.naserpour.sportclub;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
/**
* Created by Mohammad Naserpour on 9/22/2016.
*/
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
and also my login.php script:
<?php
define("HOST","localhost");
define("USERNAME","root");
define("PASSWORD","");
define("NAME","users");
$con = mysqli_connect(HOST,USERNAME,PASSWORD,NAME);
$username = $_GET["username"];
$password = $_GET["password"];
$sql = "SELECT * FROM userinfo WHERE username ='$username' AND password='$password'";
$check = mysqli_fetch_array(mysqli_query($con,$sql));
if(isset($check)){
echo '{"result":[{"response":"true"}]}';
}else{
echo '{"result":[{"response":"false"}]}';
}
mysqli_close($con);
?>
i would be so happy if i find out the problem. thank you.
see this tutorial :
its a full tutorial about login process using google volley
First : On device side, Use volley, its simple and easy to use
Second : On server, what is {"result":[{"response":"true"}]}
any problem with {"result":true} ??
Last but not the least : Did you use JSON before or this code is trial and error copy paste from some tutorials?
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);
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!!!!
Im new to Android and I need a little help. I have a class witch values from one table located on remote mysql and its working fine on 2.3 but on 4.x Im getting errors when I start it. I have read somewhere its because I`m not using AsyncTask. I tried to implement it on existing working code but there is one error, so please help because I tried everything to get this to work but no success.
Here is the existing code that works on 2.3
package com.stole.fetchtest;
import java.io.BufferedReader;
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.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.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.net.ParseException;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class FetchData extends ListActivity {
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<?> nameValuePairs = new ArrayList<Object>();
List<String> r = new ArrayList<String>();
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.url.com/fetch.php");
httppost.setEntity(new UrlEncodedFormEntity(
(List<? extends NameValuePair>) nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
r.add(json_data.getString("names"));
}
setListAdapter(new ArrayAdapter<String>(this, R.layout.names_row, r));
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), e1.toString(), Toast.LENGTH_LONG)
.show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(), e1.toString(), Toast.LENGTH_LONG)
.show();
}
}}
And then I tried to add AsyncTask, according to some tutorials found online, and it`s looking like this:
package com.stole.fetchtest;
import java.io.BufferedReader;
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.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.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class FetchData extends ListActivity {
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<?> nameValuePairs = new ArrayList<Object>();
List<String> r = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new task().execute();
}
public class task extends AsyncTask<String, String, Void> {
#SuppressWarnings("unchecked")
#Override
protected Void doInBackground(String... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.url.com/fetch.php");
httppost.setEntity(new UrlEncodedFormEntity(
(List<? extends NameValuePair>) nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
return null;
}
protected void onPostExecute(Void v) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
r.add(json_data.getString("naziv"));
}
setListAdapter(new ArrayAdapter(this, R.layout.names_row, r));
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), e1.toString(),
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(), e1.toString(),
Toast.LENGTH_LONG).show();
}
}
}
}
The error I`m getting is at
setListAdapter(new ArrayAdapter(this, R.layout.names_row, r));
and it says "The constructor ArrayAdapter(FetchData.task, int, List) is undefined"
Thanks!
it should use the activity context not the task context..
setListAdapter(new ArrayAdapter(FetchData.this, R.layout.names_row, r));