error reading string resource in java file [duplicate] - java

This question already has answers here:
error reading xml string in java file [duplicate]
(2 answers)
Closed 5 years ago.
Error:(90, 20) error: incompatible types: int cannot be converted to String
How to fix the error
in lineR.string.Invalid_city_name
using the method
getstring(R. string.Invalid_city_name)
the same error what is wrong?
status="success";
}else{
status=R.string.Invalid_city_name;
}
full Code:
package com.nbdev.app.weatherapp.json;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONObject;
import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.nbdev.app.weatherapp.ActivityMain;
import com.nbdev.app.weatherapp.adapter.ItemLocationAdapter;
import com.nbdev.app.weatherapp.data.Constant;
import com.nbdev.app.weatherapp.data.DatabaseManager;
import com.nbdev.app.weatherapp.data.GlobalVariable;
import com.nbdev.app.weatherapp.model.City;
import com.nbdev.app.weatherapp.R;
import com.nbdev.app.weatherapp.model.ForecastResponse;
import com.nbdev.app.weatherapp.model.ItemLocation;
import com.nbdev.app.weatherapp.model.WeatherResponse;
public class JSONLoader extends AsyncTask<String, String, ItemLocation>{
private JSONParser jsonParser = new JSONParser();
private String jsonWeather = null,
jsonForecast= null,
status="null";
private Context ctx;
private LinearLayout lyt_form;
private LinearLayout lyt_progress;
private TextView tv_message;
private Dialog dialog;
private DatabaseManager db;
private GlobalVariable global;
private ActivityMain act;
public JSONLoader(ActivityMain act, LinearLayout lyt_form, LinearLayout lyt_progress, TextView tv_message, Dialog dialog) {
this.act=act;
this.ctx=act.getApplicationContext();
this.lyt_form=lyt_form;
this.lyt_progress=lyt_progress;
this.tv_message=tv_message;
this.dialog=dialog;
global = (GlobalVariable) act.getApplication();
db = new DatabaseManager(act);
}
#Override
protected void onPreExecute() {
lyt_form.setVisibility(View.GONE);
lyt_progress.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected ItemLocation doInBackground(String... params) {
ItemLocation itemLocation = new ItemLocation();
try {
Thread.sleep(50);
List<NameValuePair> param = new ArrayList<NameValuePair>();
City city = db.getWordsFormAutocomplate(params[0]);
if(city!=null){
itemLocation.setId(city.getId());
itemLocation.setName(city.getName());
itemLocation.setCode(city.getCode());
String url_weather = Constant.getURLweather(city.getId());
String url_forecast = Constant.getURLforecast(city.getId());
JSONObject json_weather = jsonParser.makeHttpRequest(url_weather,"POST", param);
JSONObject json_forecast = jsonParser.makeHttpRequest(url_forecast,"POST", param);
jsonWeather = json_weather.toString();
jsonForecast = json_forecast.toString();
itemLocation.setJsonWeather(jsonWeather);
itemLocation.setJsonForecast(jsonForecast);
status="success";
}else{
status=(R.string.Invalid_city_name();
}
} catch (Exception e) {
status = e.getMessage();
e.printStackTrace();
}
return itemLocation;
}
protected void onPostExecute(ItemLocation result) {
lyt_form.setVisibility(View.VISIBLE);
lyt_progress.setVisibility(View.GONE);
if(status.equals("success")){
global.saveLocation(result);
act.refreshList();
dialog.dismiss();
}
tv_message.setText(status);
//Toast.makeText(ctx, status, Toast.LENGTH_LONG).show();
};
}

You need a context/Activity to get string from your resources.
change this:
status=R.string.Invalid_city_name;
to this
status=act.getString(R.string.Invalid_city_name);

Related

Android Studio - Import data from csv and show in text (app crashes)

I am trying to import data from a csv file but my application crashes everytime. Below is my code that I have written. I receive no errors.
My main aim is to import data from the specified csv file and put in the variable called count_car. I want to show the value in the text box when I click the button. But I could not import the data from csv file.
package com.example.deneme2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.String;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView text_zeros = findViewById(R.id.TextNumberZero);
TextView text_ones = findViewById(R.id.TextNumberOne);
TextView textView = findViewById(R.id.textView);
TextView textView1 = findViewById(R.id.textView2);
Button button = findViewById(R.id.button);
String path = "C:\\Users\\baran\\Desktop\\FALL 2020\\ELEC491\\deneme\\11111111111\\venv\\numberofcars.csv";
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
BufferedReader csvReader = null;
try {
csvReader = new BufferedReader(new FileReader(path));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String count_car = null;
int counting =0;
while (true) {
try {
if (!((count_car = csvReader.readLine()) != null)) break;
} catch (IOException e) {
e.printStackTrace();
}
//String[] data = count_car.split(",");
String count_cars = count_car;
int count_park= 100;
String countpark = String.valueOf(count_park);
String countcars = String.valueOf(count_cars);
text_ones.setText(countpark);
text_zeros.setText(countcars);
counting = counting +1 ;
if (counting == 50);
break;
}
}
});
}
}
EDIT 1
package com.example.exceldeneme;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.String;
import java.util.List;
public class MainActivity<number_cars> extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView text_cars = findViewById(R.id.textCars);
readData();
String count_park = Arrays.toString(number_of_cars.get(1));
text_cars.setText(count_park);
}
private List<String[]> number_of_cars = new ArrayList<>();
private void readData() {
InputStream is = getResources().openRawResource(R.raw.numberofcars);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8"))
);
String line = "";
try {
while(((line = reader.readLine()) != null)) {
String[] tokens = line.split(",");
number_of_cars.add(tokens);
Log.d("MyActivity","Just created"+ Arrays.toString(tokens));
}
}
catch (IOException e) {
Log.wtf("MyActivity","Error reading data file on line" + line, e);
e.printStackTrace();
}
}
}
I have changed the code. Now I am using different method. But the app starts to crash again. Is there any opinion? Thanks for answers.
EDIT 2
package com.example.exceldeneme;
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.String;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class MainActivity<number_cars> extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoView videoView = findViewById(R.id.video_view);
Button button = findViewById(R.id.button);
TextView text_cars = findViewById(R.id.textEmpty);
TextView text_total_lots = findViewById(R.id.textTotalLots);
readData();
int number_of_park = 100;
text_total_lots.setText(String.valueOf(number_of_park));
int counter = 0;
String videoPath = "android.resource://" + getPackageName() + "/" + R.raw.camera_out;
Uri uri = Uri.parse(videoPath);
videoView.setVideoURI(uri);
MediaController mediaController = new MediaController(this);
videoView.setMediaController(mediaController);
mediaController.setAnchorView(videoView);
//Log.d("Selam","This is my message"+ number_of_cars.get(0)[0]);
//String count_park = number_of_cars.get(0)[2];
//text_cars.setText(count_park);
for (String i : number_of_cars.get(0)){
counter = counter + 1 ;
}
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int counter = 0;
for (String i : number_of_cars.get(0)){
counter = counter + 1 ;
}
for (int i = 1; i < counter-1;i= i +1){
String count_park = number_of_cars.get(0)[i];
text_cars.setText(count_park);
//SystemClock.sleep(1000); //ms
Log.d("Selam","SORUN YOK");
}
}
});
}
private ArrayList<String[]> number_of_cars = new ArrayList<String[]>();
private void readData() {
InputStream is = getResources().openRawResource(R.raw.numberofcars);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8"))
);
String line = "";
try {
while(((line = reader.readLine()) != null)) {
String[] tokens = line.split(",");
number_of_cars.add(tokens);
Log.d("MyActivity","Just created"+ Arrays.toString(tokens));
}
}
catch (IOException e) {
Log.wtf("MyActivity","Error reading data file on line" + line, e);
e.printStackTrace();
}
}
}
My final code is here. I have solved my problems and imported data from csv file. I have used videoview to show video. Now I am trying to solve the delay problem.
I want the below for loop function to wait for 1 second or 50 ms. But I could not find the solution.
for (int i = 1; i < counter-1;i= i +1){
String count_park = number_of_cars.get(0)[i];
text_cars.setText(count_park);
//SystemClock.sleep(1000); //ms
Log.d("Selam","SORUN YOK");
}
If anyone can help, I appreciate it :) Thanks for your answers.

Handler not executing in android studio

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.

Android studio connecting to remote database

I am trying to get an Android Studio app to connect to a remote server hosted on "hostbuddy". Here is the code (when sending data the error is "Connection goes wrong 2") making me guess there is something wrong with the DB_URL. I tried changing the url in many ways, none worked. If it would help I could also post the logcat.
EDIT : I fixed it, i forgot to add the module for the connector for MySQl, works like a charm now ^_^
package com.example.battl.qr2;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Register extends AppCompatActivity {
TextView textView;
Button button;
EditText editText;
private static final String DB_URL= "jdbc:mysql://mysql6002.site4now.net/db_a37d85_mydb:3306";
private static final String USER = "X";
private static final String PASS = "X";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
textView=(TextView) findViewById(R.id.textView);
editText=(EditText) findViewById(R.id.editText);
}
public void btnConn(View view)
{
Send objsend = new Send();
objsend.execute("");
}
private class Send extends AsyncTask<String,String,String>
{
String msg = "";
String text = editText.getText().toString();
#Override
protected void onPreExecute() {textView.setText("Please Wait Inserting");}
#Override
protected String doInBackground(String... strings)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
if(conn == null) {
msg="Connection goes wrong";
} else {
String query = "INSERT INTO ex (col1) VALUES ('"+text+"') ";
Statement stmt = conn.createStatement();
stmt.executeUpdate(query);
msg = "Inserted successfully";
}
conn.close();
}
catch (Exception e)
{
msg="Connection goes wrong 2";
e.printStackTrace();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {textView.setText(msg);}
}
}

Could not find class 'EndpointsAsyncTask$1', referenced from method EndpointsAsyncTask.xxx - Anonymous function

I'm struggling from two days now with this issue, I can't understand why is this happening, I have this EndpointAsyncTask java class on my Android Project (I'm using android Studio 1.2.2):
package com.kkoci.shairlook;
/**
* Created by kristian on 02/07/2015.
*/
import android.content.Context;
import android.os.AsyncTask;
import android.util.Pair;
import android.widget.Toast;
import com.appspot.shairlook1.userEndpoint.UserEndpoint;
import com.appspot.shairlook1.userEndpoint.model.User;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
public class EndpointsAsyncTask extends AsyncTask<Void, Void, List<User>> implements GoogleClientRequestInitializer{
private static UserEndpoint myApiService = null;
private Context context;
EndpointsAsyncTask(Context context) {
this.context = context;
}
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
}
class MyClass{}
#Override
protected List<User> doInBackground(Void... params) {
if(myApiService == null) { // Only do this once
UserEndpoint.Builder builder = new UserEndpoint.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://localhost:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
// end options for devappserver
myApiService = builder.build();
}
try {
return myApiService.listUser().execute().getItems();
} catch (IOException e) {
return Collections.EMPTY_LIST;
}
}
#Override
protected void onPostExecute(List<User> result) {
for (User q : result) {
Toast.makeText(context, q.getWho() + " : " + q.getWhat(), Toast.LENGTH_LONG).show();
}
}
}
And I call this method from an Activity, like this:
package com.kkoci.shairlook;
import android.app.Activity;
//import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.database.SQLException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.view.LayoutInflater;
import com.appspot.shairlook1.userEndpoint.UserEndpoint;
import com.appspot.shairlook1.userEndpoint.model.User;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import com.kkoci.shairlook.R;
import com.facebook.FacebookSdk;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
/**
* Created by kristian on 26/04/2015.
*/
public class LoginMember extends Activity {
private static
EditText txtPassword;
EditText txtEmail;
Button btnLogin;
TextView Forgot_text;
Button twitter;
Button facebook;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtPassword = (EditText) findViewById(R.id.et_pw);
txtEmail = (EditText) findViewById(R.id.et_email);
btnLogin = (Button) findViewById(R.id.btn_login);
twitter = (Button) findViewById(R.id.twitter);
facebook = (Button) findViewById(R.id.facebook);
Forgot_text = (TextView) findViewById(R.id.Forgot_text);
}
public void getUser(View v) {
new EndpointsAsyncTask(this).execute();
}
}
Here's the method: public void getUser(View v) { new EndpointsAsyncTask(this).execute(); }
Always compiles fine, but on runtime execution, if I click on a button which invokes this anonymous function it throws me an error saying this:
Could not find class 'com.kkoci.shairlook.EndpointsAsyncTask$1', referenced from method com.kkoci.shairlook.EndpointsAsyncTask.doInBackground
07-02 20:17:18.210 20901-21027/com.kkoci.shairlook E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NoClassDefFoundError: com.kkoci.shairlook.EndpointsAsyncTask$1
at com.kkoci.shairlook.EndpointsAsyncTask.doInBackground(EndpointsAsyncTask.java:41)
at com.kkoci.shairlook.EndpointsAsyncTask.doInBackground(EndpointsAsyncTask.java:22)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
            
This is how I call the function from my button:
<Button
android:id="#+id/twitter"
android:layout_width="50dp"
android:layout_height="50dp"
android:text="Register with Twitter"
android:textColor="#FFF"
android:layout_marginBottom="10dp"
android:textSize="20dp"
android:layout_marginTop="11dp"
android:layout_marginLeft="30dp"
android:background="#drawable/twitter_button"
android:onClick="getUser"/>
Any ideas? I really can't understand what is the problem, please, help,
Thanks in advance!
PS = BTW I was following this tutorial Consuming endpoints on android app
Try this code:
package com.kkoci.shairlook;
/**
* Created by kristian on 02/07/2015.
*/
import android.content.Context;
import android.os.AsyncTask;
import android.util.Pair;
import android.widget.Toast;
import com.appspot.shairlook1.userEndpoint.UserEndpoint;
import com.appspot.shairlook1.userEndpoint.model.User;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
public class EndpointsAsyncTask extends AsyncTask<Void, Void, List<User>> implements GoogleClientRequestInitializer{
private static UserEndpoint myApiService = null;
private Context context;
EndpointsAsyncTask(Context context) {
this.context = context;
}
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
// put it here no in MyClass
abstractGoogleClientRequest.setDisableGZipContent(true);
}
// class MyClass{} // you don't need it
#Override
protected List<User> doInBackground(Void... params) {
if(myApiService == null) { // Only do this once
UserEndpoint.Builder builder = new UserEndpoint.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://localhost:8080/_ah/api/")
.setGoogleClientRequestInitializer(this);
// end options for devappserver
myApiService = builder.build();
}
try {
return myApiService.listUser().execute().getItems();
} catch (IOException e) {
return Collections.EMPTY_LIST;
}
}
#Override
protected void onPostExecute(List<User> result) {
for (User q : result) {
Toast.makeText(context, q.getWho() + " : " + q.getWhat(), Toast.LENGTH_LONG).show();
}
}
}

Consuming Restful WCF Service in Android

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!!!!

Categories