Fetch sms From phone and upload on server - java

Here i am fetch sms from phone and upload 10 sms on server all code working fine but instead of 10 sms upload to server only Specific one sms uploaded 10 time to server, pls tell me what i am missing in my code?
here is my message_class.Java code.
public class message_class extends Activity{
int j = 0;
Button btninbox;
ListView lstView;
SimpleCursorAdapter adapter;
ArrayList<Message_Item> msg_list;
String Str_Msg, Str_Phone,dated;
Msg_adapter msg_adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.msginbox_layout);
msg_list = new ArrayList<Message_Item>();
btninbox = (Button) findViewById(R.id.btn_inbox);
btninbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(message_class.this, Msg_Recive.class);
startActivity(intent);
}
});
lstView = (ListView) findViewById(R.id.lv_msg);
fetchInbox();
final int arraysize = msg_list.size();
for (int j=0; j<10;j++){
Str_Msg = msg_list.get(j).getStrMsg().toString();
Str_Phone = msg_list.get(j).getStrNumber().toString();
Toast.makeText(message_class.this, Str_Phone+" "+Str_Msg, Toast.LENGTH_LONG).show();
new HttpAsyncTask()
.execute("http://demo.glowsosl.com/synchs_dsda_app/insert_details_msg.php");
msg_adapter.notifyDataSetChanged();
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
Contacts person = new Contacts();
person.setPhone(Str_Phone);
person.setName(Str_Msg);
return POST(urls[0], person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result + "Data Sent!",
Toast.LENGTH_LONG).show();
}
}
private static String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public static String POST(String url, Contacts person) {
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("contact_no", person.getPhone());
jsonObject.accumulate("sim_num", "Unknown");
jsonObject.accumulate("msg", person.getName());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the
// content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result + "," + person.getName() + ","
+ person.getPhone();
}
ArrayList<String> jsonStringToArray(String jsonString) throws JSONException {
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
stringArray.add(jsonArray.getString(i));
}
return stringArray;
}
public void fetchInbox() {
// ArrayList sms = new ArrayList();
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(uriSms,
new String[] { "_id", "address", "date", "body" }, null, null,
null);
//for (int i =0; i<((JSONArray) cursor).length();i++){
//Toast.makeText(getApplicationContext(), "work", Toast.LENGTH_SHORT).show();
//}
cursor.moveToFirst();
while (cursor.moveToNext()) {
String address = cursor.getString(1);
String date = cursor.getString(2);
String body = cursor.getString(3);
// Toast.makeText(getApplicationContext(), cursor.getString(2), Toast.LENGTH_SHORT).show();
msg_list.add(new Message_Item(address, body,date));
}
msg_adapter = new Msg_adapter(msg_list, message_class.this);
lstView.setAdapter(msg_adapter);
}

Instead of applying for loop out side async task use it in doInBackground method.
Your doInBackground method will look like follows.
#Override
protected String doInBackground(String... urls) {
String result="";
for(int i = 0; i < msg_list.size(); i++){
Str_Msg = msg_list.get(i).getStrMsg().toString();
Str_Phone = msg_list.get(i).getStrNumber().toString();
Contacts person = new Contacts();
person.setPhone(Str_Phone);
person.setName(Str_Msg);
result= result + POST(urls[0], person);
}
return result;
}
And call this async task only once.
Enjoy!!

Related

How to get the JSON error response and toast it?

Here's my code for when i trying to register user and need a toast which is response from server regarding user already exist. i can post successfully to server using json but if there's response i have to idea how to catch it the image shows example when using postman.
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
private EditText signupInputName, signupInputEmail, signupInputPassword, retypeInputPassword;
private Button btnSignUp;
private Button btnLinkLogin;
private String message = "";
private int code = 0;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
signupInputName = (EditText) findViewById(R.id.signup_input_name);
signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
retypeInputPassword = (EditText) findViewById(R.id.signup_retype_password);
btnSignUp = (Button) findViewById(R.id.btn_signup);
btnLinkLogin = (Button) findViewById(R.id.btn_link_login);
btnSignUp.setOnClickListener(this);
btnLinkLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(i);
}
});
}
public String POST(String url, Person person)
{
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httppost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("user_name", person.getUsername());
jsonObject.accumulate("email", person.getEmail());
jsonObject.accumulate("password", person.getPassword());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httppost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httppost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Error! email exist";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
#Override
public void onClick(View view) {
if(validate() == 1)
{
Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
}
else if (validate() == 2)
{
Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
}
else if (validate() == 3)
{
Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
}
else if (validate() == 4)
{
//Toast.makeText(getBaseContext(), "Success", Toast.LENGTH_SHORT).show();
new HttpAsyncTask().execute("http://ip-addressses/api/register");
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls) {
person = new Person();
person.setUsername(signupInputName.getText().toString());
person.setEmail(signupInputEmail.getText().toString());
person.setPassword(signupInputPassword.getText().toString());
return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
JSONObject jObject;
try {
jObject = new JSONObject(result);
if (jObject.has("error")) {
String aJsonString = jObject.getString("error");
Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
private int validate() {
if(signupInputName.getText().toString().trim().equals("") || signupInputEmail.getText().toString().trim().equals("") || signupInputPassword.getText().toString().trim().equals("") || retypeInputPassword.getText().toString().trim().equals(""))
{
code = 1;
message = "Complete the form!";
}
else if (!(signupInputPassword.getText().toString().equals(retypeInputPassword.getText().toString())))
{
code = 2;
message = "Re-check password";
}
else if (!isValidEmail(signupInputEmail.getText().toString()) ) {
code = 3;
message = "Invalid email";
}
else
code = 4;
return code;
}
public final static boolean isValidEmail(String target)
{
if (target == null) {
return false;
} else {
Matcher match = Patterns.EMAIL_ADDRESS.matcher(target);
return match.matches();
}
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
Postman response when email exist
Just change this code:
jObject = new JSONObject(result);
if (jObject.has("error"))
{
String aJsonString = jObject.getString("error");
Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
Toast.makeText(getBaseContext(),result+"" , Toast.LENGTH_SHORT).show();
}
So by this code, if your response is not JSON it will throw exception in catch. And here you can show toast.

Set Progressbar with percentage when data download from json get method in android

I want to show progress bar with percentage of the download the data from json. Right now I am getting the data from the url and store in the local database in other class and this class called in MainActivity. Now I want to show the progressbar with percentage of the download file from json url.
This is my code
public class Web_Product {
Context context;
List<Variable> list = new ArrayList<Variable>();
//List<Variable> list1;
String url = "https://api.androidhive.info/progressdialog/hive.jpg";
URL url1 = null;
InputStream is1 = null;
String product_id, product_name, product_image;
private byte[] logoImage;
private JSONArray jsonArray;
public Web_Product(Context context) {
this.context = context;
Log.e("hello", "Message");
}
public void product_insert() {
// new AsyncLogin().execute();
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.e("TEST", "jsonStr:-" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonRootObject = new JSONObject(jsonStr);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("product");
//Iterate the jsonArray and print the info of JSONObjects
for (int i = 0; i < jsonArray.length(); i++) {
Log.e("TEST_P", "in");
JSONObject details = jsonArray.getJSONObject(i);
product_id = details.getString("product_id");
product_name = details.getString("product_name");
product_image = details.getString("product_image");
logoImage = getLogoImage(product_image);
Variable variable_object = new Variable();
variable_object.setProduct_id(product_id);
variable_object.setProduct_name(product_name);
variable_object.setProduct_url_image(logoImage);
list.add(variable_object);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
Log.e("TEST1", " Ritunjay" + list.size());
Product_data product = new Product_data(context);
product.Insert_Product(list);
Log.e("listpo", "" + list);
}
public JSONArray json_web_prod() {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.e("TEST", "jsonStr:-" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonRootObject = new JSONObject(jsonStr);
//Get the instance of JSONArray that contains JSONObjects
jsonArray = jsonRootObject.optJSONArray("product");
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray;
}`
Main Activity
class add extends AsyncTask<String, Integer, String> {
ProgressDialog mProgressDialog;
#Override
protected void onProgressUpdate(Integer... values) {
mProgressDialog.setProgress(values[0]);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Downloading Data...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
mProgressDialog.dismiss();
flag = true;
Intent intent = getIntent();
startActivity(intent);
finish();
Log.e("flag , post", "" + flag);
}
#Override
protected String doInBackground(String... params) {
web_product = new Web_Product(getApplicationContext());
web_product.product_insert();
return null;
}
}`
In doInBackground , you need to publishProgress also . So that your progress bar can updated , like this
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
Here totalSize will help you to calculate your total remaining data and publishProgress will public it .

android how to make ListView refresh every 5 sec

I have ListView which have data . Data come from server and I want the ListView to update after every 5 sec. How to do this? I am new to android development. Please help me. Here is my code..
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for (int i = 0; i < peoples.length(); i++) {
JSONObject c = peoples.getJSONObject(i);
String data = c.getString(TAG_DATA);
final String dataaaa = rcdata.getText().toString().trim();
HashMap<String, String> user_data = new HashMap<String, String>();
user_data.put(TAG_DATA, data);
personList.add(user_data);
}
ListAdapter adapter = new SimpleAdapter(
DataSendActivity.this, personList, R.layout.layout_chat,
new String[]{TAG_DATA},
new int[]{R.id.data}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
also tried this onCreate
final Handler handler = new Handler();
handler.postDelayed( new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
handler.postDelayed( this, 5000 );
}
}, 5000 );
i get data with this method
public void getData() {
class GetDataJSON extends AsyncTask<String, Void, String> {
//String recID = ;
//String userID = email;
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HashMap<String, String> user = db.getUserDetails();
//String name = user.get("name");
// Semail = user.get("email");
String semail = user.get("email");
final String remail = rremail;
HttpPost httppost = new HttpPost("http://samplechatapp.gear.host/myphpfile.php?sender_email="+semail+"&reciver_email="+remail+"&fatch_server_data=true");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
Log.i("","processing entity");
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
Log.i("",line);
}
result = sb.toString();
Log.i("",result);
} catch (Exception e) {
// Oops
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
but when i open the listview app crash please help me i am very new in android
You should call the api after you get the response from the first api call . You can notifyDataSetChanged() post that .
Call notifyDataSetChanged() whenever there is change in data.
Moreover avoid using ListView instead of that start using RecyclerView.

How to access json array that is passed from restful web service in android?

I have successfully created a rest web service and it returns jsonarray which has two fields
id and city from data base.
My resr web service is
#GET
#Path("city")
#Produces("application/json")
public String getJson() {
PropertyPojo propojo=null;
ArrayList cityList = new ArrayList();
JSONArray list = new JSONArray();
Map m1 = new LinkedHashMap();
List l1 = new LinkedList();
String jsonString = null;
try{
cityList=PDao.CityList();
Iterator it=cityList.iterator();
while(it.hasNext())
{
propojo=(PropertyPojo)it.next();
m1.put(propojo.getKeyid(),propojo.getKeyvalue());
}
}catch(Exception e){
}
l1.add(m1);
jsonString = JSONValue.toJSONString(l1);
return jsonString;
}
I just need to put these values into a spinner...
My android code is
public class MainActivity extends Activity {
Spinner spinner;
private static final String SERVICE_URL = "http://192.168.1.6:8080/eSava_RestWeb/webresources/service";
private static final String TAG = "AndroidRESTClientActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner = (Spinner) findViewById(R.id.city);
}
public void retrieveSampleData(View vw) {
String sampleURL = SERVICE_URL + "/city";
WebServiceTask wst = new WebServiceTask(WebServiceTask.GET_TASK,
this, "GETting data...");
wst.execute(new String[] { sampleURL });
}
#SuppressLint("NewApi")
public void handleResponse(String response) {
try {
// JSONObject jso = new JSONObject(response);
JSONArray json = new JSONArray(response);
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray) json;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i = 0; i < len; i++) {
list.add(jsonArray.get(i).toString());
}
}
Spinner s = (Spinner) findViewById(R.id.city);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, list);
s.setAdapter(adapter);
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
private class WebServiceTask extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
public static final int GET_TASK = 2;
private static final String TAG = "WebServiceTask";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 3000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 5000;
private int taskType = GET_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public WebServiceTask(int taskType, Context mContext,
String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity()
.getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
JSONArray jsArray;
// jsArray = new JSONArray(response);
handleResponse(response);
pDlg.dismiss();
}
// Establish connection and socket (data retrieval) timeouts
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost = new HttpPost(url);
// Add parameters
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
case GET_TASK:
HttpGet httpget = new HttpGet(url);
response = httpclient.execute(httpget);
break;
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(
new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
}
Its better to create Model class and then you can parse the response with gson.
For example,
Imagine that you have your response with two strings Name and Mail. Create a model with two strings.
public class Sample{
public Sample()
{
}
#SerializedName("Name")//if needed
String name;
#SerializedName("Email")//if needed
String email;
public void set(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void set(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}
Then parse your response with gson.
Sample sample = gson.fromJson(jsonRes.toString(), Sample.class);
Then you can access the members of the object sample. Change the Sample class as you needed(with the array of strings and int. You can use ArrayList instead of Array)
String[] city= {};
String[] id= {};
JSONArray jsonDetailsObj = json.getJSONArray("cityList");
JSONObject jsonLoop = null;
int noOfPoints = jsonDetailsObj.length();
city= new String[noOfPoints];
id= new String[noOfPoints];
for (int i=0 ; i < noOfPoints ; i++)
{
jsonLoop=jsonDetailsObj.getJSONObject(i);
city [i] = jsonLoop.getString("CityName");
id[i] = jsonLoop.getString("ID");
}

Android Error Returning a null value from Thread

I created this application to get the wether details to my app.
I have a GetWeather Class in my Android App whre i have GetWeather method which returns a string. but when i try to get value form that class which consist of a thread. i always get a null value. Please refer my code kindly and tell me where i got wrong. Thank you
Main Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button) findViewById(R.id.showData);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
GetWeather1 gw = new GetWeather1();
String weather = gw.GetWeather1 ("CA","Anuradhapura");
Toast.makeText(getApplicationContext(), " Weather condition is " + weather, Toast.LENGTH_SHORT).show();
}
});
}
// This is GetWeather class
public class GetWeather {
public String weather;
public String temperature_string;
public Bitmap weather_icon;
public GetWeather() {
}
public String GetWeather(String city, String state) {
city = city.replaceAll(" ", "_");
// construct post URL
final String GET_WEATHER_URL = WEATHER_URL + state + "/" + city
+ ".json";
new Thread(new Runnable() {
public void run() {
String request = GET_WEATHER_URL;
HttpResponse rp = null;
JSONObject jObject = null;
try {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpGet request1 = new HttpGet(
"http://api.wunderground.com/api/key/conditions/q/CA/Anuradhapura.json");
HttpResponse response = httpclient.execute(request1);
HttpEntity resEntity = response.getEntity();
String _response = EntityUtils.toString(resEntity);
jObject = new JSONObject(_response);
JSONObject current_observation = jObject.getJSONObject("current_observation");
temperature_string = current_observation.getString("temperature_string");
weather = current_observation.getString("weather");
Log.i("..............", "" + weather);
Log.i("..............", "" + temperature_string);
String icon_url = current_observation.getString("icon_url");
weather_icon = get_weather_icon(icon_url);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
while (weather != null) {
}
return weather;
}
The condition while(whether != null) should be while(whether == null) to wait for a Thread to complete its task. But it will wait on UI Thread which may result in ANR error.
Instead use AsyncTask and get the result in onPostExecute()...
and with respect to your comments, This may help you.
public class WeatherTask extends AsyncTask<String, Void, String[]> {
#Override
protected String[] doInBackground(String... params) {
String city = params[0];
String state = params[1];
city = city.replaceAll(" ", "_");
// construct post URL
final String GET_WEATHER_URL = WEATHER_URL + state + "/" + city
+ ".json";
String request = GET_WEATHER_URL;
HttpResponse rp = null;
JSONObject jObject = null;
try {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpGet request1 = new HttpGet(
"http://api.wunderground.com/api/key/conditions/q/CA/Anuradhapura.json");
HttpResponse response = httpclient.execute(request1);
HttpEntity resEntity = response.getEntity();
String _response = EntityUtils.toString(resEntity);
jObject = new JSONObject(_response);
JSONObject current_observation = jObject
.getJSONObject("current_observation");
String temperature_string = current_observation
.getString("temperature_string");
String weather = current_observation.getString("weather");
Log.i("..............", "" + weather);
Log.i("..............", "" + temperature_string);
String icon_url = current_observation.getString("icon_url");
String weather_icon = get_weather_icon(icon_url);
String[] out = new String[]{weather,weather_icon,temperature_string};
return out;
} catch (Exception exception) {
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
if(result != null) {
String weather = result[0];
String weather_icon = result[1];
String temperature_string = result[2];
}
}
}
and start this task in onButtonClick() like
new WeatherTask().execute("CA","Anuradhapura");

Categories