Not able to communicate between android and webserver - java

It is always giving Incorrect credentials, I have double checked the database ,Is there some issue with the code . I am new to android studio,
Any kind of help will be appreciated.
MainActivity
package com.tarun.proxy_maar;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
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 java.util.List;
public class MainActivity extends AppCompatActivity {
private EditText editTextUserName;
private EditText editTextPassword;
public static final String USER_NAME = "USERNAME";
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextUserName = (EditText) findViewById(R.id.editTextUserName);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
}
public void invokeLogin(View view){
username = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
login(username,password);
}
private void login(final String username, String password) {
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
String uname = params[0];
String pass = params[1];
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", uname));
nameValuePairs.add(new BasicNameValuePair("password", pass));
String result = null;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://shaadi.web44.net/hello.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result){
String s = result.trim();
loadingDialog.dismiss();
if(s.equalsIgnoreCase("success")){
Intent intent = new Intent(MainActivity.this, UserProfile.class);
intent.putExtra(USER_NAME, username);
finish();
startActivity(intent);
}else {
Toast.makeText(getApplicationContext(), "Invalid User Name or Password", Toast.LENGTH_LONG).show();
}
}
}
LoginAsync la = new LoginAsync();
la.execute(username, password);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
PHP SCRIPT ON WEBSERVER
<?php
define('HOST','host');
define('USER','user');
define('PASS','password');
define('DB','database');
$con = mysqli_connect(HOST,USER,PASS,DB);
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "select * from login where username='$username' and password='$password'";
$res = mysqli_query($con,$sql);
$check = mysqli_fetch_array($res);
if(isset($check)){
echo 'success';
}else{
echo 'failure';
}
mysqli_close($con);
?>
Logcat
10-11 07:57:42.852 28481-28481/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
10-11 07:57:42.852 28481-28481/? I/art﹕ Late-enabling JIT
10-11 07:57:42.856 28481-28481/? I/art﹕ JIT created with code_cache_capacity=2MB compile_threshold=1000
10-11 07:57:42.897 28481-28488/? E/art﹕ Failed writing handshake bytes (-1 of 14): Broken pipe
10-11 07:57:42.897 28481-28488/? I/art﹕ Debugger is no longer active
10-11 07:57:42.900 28481-28481/? W/System﹕ ClassLoader referenced unknown path: /data/app/com.tarun.proxy_maar-2/lib/x86
10-11 07:57:43.079 28481-28504/? D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
10-11 07:57:43.082 28481-28481/? D/﹕ HostConnection::get() New Host Connection established 0xabe7d170, tid 28481
10-11 07:57:43.135 28481-28504/? D/﹕ HostConnection::get() New Host Connection established 0xabe7d480, tid 28504
10-11 07:57:43.141 28481-28504/? I/OpenGLRenderer﹕ Initialized EGL, version 1.4
10-11 07:57:43.311 28481-28504/? W/EGL_emulation﹕ eglSurfaceAttrib not implemented
10-11 07:57:43.311 28481-28504/? W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xad7918a0, error=EGL_SUCCESS
10-11 07:58:56.273 28481-28504/com.tarun.proxy_maar W/EGL_emulation﹕ eglSurfaceAttrib not implemented
10-11 07:58:56.274 28481-28504/com.tarun.proxy_maar W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xad7bf200, error=EGL_SUCCESS
10-11 07:58:56.939 28481-28504/com.tarun.proxy_maar E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab815a40
10-11 07:58:57.128 28481-28504/com.tarun.proxy_maar W/EGL_emulation﹕ eglSurfaceAttrib not implemented
10-11 07:58:57.128 28481-28504/com.tarun.proxy_maar W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa2e1e6c0, error=EGL_SUCCESS
10-11 07:59:00.474 28481-28504/com.tarun.proxy_maar E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab8159d0

I use the jsoup library to post data from my android apps and it's way easier, where's an example
Document doc = Jsoup.connect("http://shaadi.web44.net/hello.php")
.data("username", uname)
.data("password", pass)
.userAgent("some user agent..or not...")
.timeout(30000)
.post();
String httpresponse = doc.text();

Related

stuck in getting arraylist from another class in android

I’m making a project in which i get data through api and stored it in arraylist but when i return it, it is empty.
Can Anyone Help Me Out?
Here is the Main Activity
package com.example.trivia;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import com.example.trivia.Data.Async;
import com.example.trivia.Data.setQ;
import com.example.trivia.controller.AppController;
import com.example.trivia.model.question;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private CardView c;
private Button t_btn,f_btn;
private ImageButton next,prev;
private List<question>q;
private TextView set;
private int count=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
c=findViewById(R.id.cardView);
t_btn=findViewById(R.id.true_btn);
f_btn=findViewById(R.id.false_btn);
next=findViewById(R.id.next);
prev=findViewById(R.id.prev);
set=findViewById(R.id.setq);
//ArrayList<question> dummy = new ArrayList<question>();
//AppController.OnCreate();
q=new setQ().getData(new Async() {
#Override
public void finish(ArrayList<question> c) {
set.setText(c.get(count).getQ());
// Log.d("test", "onCreate: "+c);
}
});
Log.i("in main", "Main: "+q.size());
}
}
the code of setQ class
package com.example.trivia.Data;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.trivia.controller.AppController;
import com.example.trivia.model.question;
import org.json.JSONArray;
import org.json.JSONException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class setQ {
ArrayList<question> q =new ArrayList<question>();
JSONArray r;
private String url="https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json";
public List<question> getData(final Async call) {
final JsonArrayRequest jarr = new JsonArrayRequest(Request.Method.GET, url, (JSONArray)null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
r=response;
for (int i = 0; i < response.length(); i++) {
try {
JSONArray a = response.getJSONArray(i);
question k = new question(a.getString(0), a.getBoolean(1));
//Log.i("list", "onResponse: "+k.getAns());
q.add(k);
// Log.i("response", "onResponse: " +a.get(0));
} catch (JSONException e) {
e.printStackTrace();
}
}
if(call!=null) {
call.finish( q);
}
//return q;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Log.i("error ",""+AppController.getInstance());
AppController.getInstance().addToRequestQueue(jarr);
return q;
// return q;
}
}
output
07/11 23:55:18: Launching 'app' on Pixel 3 API 21.
$ adb shell am start -n "com.example.trivia/com.example.trivia.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 15594 on device 'emulator-5554'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
I/error: com.example.trivia.controller.AppController#24777a64
***I/in main: Main: 0***
D/OpenGLRenderer: Render dirty regions requested: true
D/: HostConnection::get() New Host Connection established 0x7f28894105c0, tid 15594
D/Atlas: Validating map...
I/art: Background sticky concurrent mark sweep GC freed 5802(428KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 2MB/2MB, paused 8.789ms total 42.738ms
D/: HostConnection::get() New Host Connection established 0x7f28950b0e40, tid 15624
I/OpenGLRenderer: Initialized EGL, version 1.4
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0x7f2894773200: maj 3 min 1 rcv 4
D/EGL_emulation: eglMakeCurrent: 0x7f2894773200: ver 3 1 (tinfo 0x7f289470fe40)
E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
glUtilsParamSize: unknow param 0x00008824
D/OpenGLRenderer: Enabling debug mode 0
D/EGL_emulation: eglMakeCurrent: 0x7f2894773200: ver 3 1 (tinfo 0x7f289470fe40)
I/Choreographer: Skipped 62 frames! The application may be doing too much work on its main thread.
Implement the callback pattern.
Create a new Interface file:
Interface MyVolleyResponse {
void onResponse(JSONArray response);
void onError(VolleyError error);
}
Your activity should implement this, as follows:
public class MainActivity extends AppCompatActivity implements MyVolleyResponse {...}
Add the new methods to your activity:
void onResponse(JSONArray response) {
// process your response here, building your question array...
}
void onError(VolleyError error) {
// handle errors here...
}
Change your Volley responses within SetQ:
public void onResponse(JSONArray response) {
callback.onResponse(response);
}
public void onErrorResponse(VolleyError error) {
callback.onError(error);
}
Create a constructor within SetQ to set the callback:
private MyVolleyResponse callback;
SetQ(MyVolleyResponse callback) {
this.callback = callback;
}
Call this constructor in your activity with:
SetQ volley = new SetQ(this);
Change the signnature of getData to just:
void getData() {...}
And run the Volley call with volley.getData().
Remove all AsyncTask objects in your code, because Volley is already asynchronous.

AsyncTask task onPostExecute() not executing? Tried all answer already present on stackoverflow

Hi Developers and friends,
I am working on an android application, which required to read JSON url. I am using AsyncTask. But I dont know why the onPostExecute() is not executing. I successfully parse the json. The only thing left is to return the string (having parse json text).
Here is my code:
package com.vijay.jsonwizard.demo.activities;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.vijay.jsonwizard.demo.R;
import com.vijay.jsonwizard.activities.JsonFormActivity;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private static final int REQUEST_CODE_GET_JSON = 1;
private static final String TAG = "MainActivity";
private static final String DATA_JSON_PATH = "http://jatinderbhola.in/phppractice/data.json";
String json;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button_start).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, JsonFormActivity.class);
BackgroundTask task = new BackgroundTask();
task.execute();
if (json != null) {
intent.putExtra("json", json);
startActivityForResult(intent, REQUEST_CODE_GET_JSON);
} else {
Toast.makeText(getApplicationContext(), "Error!!", Toast.LENGTH_LONG).show();
}
}
});
}
private class BackgroundTask extends AsyncTask < String, String, String > {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String...params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(DATA_JSON_PATH)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
try {
//Log.d("Respose", response.body().string());
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String data) {
set_json(data);
}
}
private void set_json(String s) {
// json = s;
Toast.makeText(getApplicationContext(), "I'm in!!", Toast.LENGTH_LONG).show();
}
}
Thanks and advance.
no exception:
this is what android monitor displaying:
01-28 13:42:17.117 1450-1450/com.vijay.jsonwizard.demo I/art: Not late-enabling -Xcheck:jni (already on)
01-28 13:42:17.117 1450-1450/com.vijay.jsonwizard.demo I/art: Late-enabling JIT
01-28 13:42:17.119 1450-1450/com.vijay.jsonwizard.demo I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
01-28 13:42:17.147 1450-1450/com.vijay.jsonwizard.demo W/System: ClassLoader referenced unknown path: /data/app/com.vijay.jsonwizard.demo-1/lib/x86
01-28 13:42:17.309 1450-1477/com.vijay.jsonwizard.demo D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
01-28 13:42:17.411 1450-1477/com.vijay.jsonwizard.demo I/OpenGLRenderer: Initialized EGL, version 1.4
01-28 13:42:17.805 1450-1458/com.vijay.jsonwizard.demo W/art: Suspending all threads took: 31.806ms
01-28 13:42:17.935 1450-1477/com.vijay.jsonwizard.demo W/EGL_emulation: eglSurfaceAttrib not implemented
01-28 13:42:17.935 1450-1477/com.vijay.jsonwizard.demo W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad7600e0, error=EGL_SUCCESS
01-28 13:42:17.991 1450-1450/com.vijay.jsonwizard.demo I/Choreographer: Skipped 38 frames! The application may be doing too much work on its main thread.
01-28 13:43:25.890 1450-1458/com.vijay.jsonwizard.demo W/art: Suspending all threads took: 5.563ms
01-28 13:49:09.646 1450-1458/com.vijay.jsonwizard.demo W/art: Suspending all threads took: 6.337ms
01-28 13:56:08.565 1450-1477/com.vijay.jsonwizard.demo W/EGL_emulation: eglSurfaceAttrib not implemented
01-28 13:56:08.566 1450-1477/com.vijay.jsonwizard.demo W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad7603e0, error=EGL_SUCCESS
01-28 13:56:11.892 1450-1477/com.vijay.jsonwizard.demo E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4053c00
move the next code to PostExecute stage:
Intent intent = new Intent(MainActivity.this, JsonFormActivity.class);
if (json != null) {
intent.putExtra("json", json);
startActivityForResult(intent, REQUEST_CODE_GET_JSON);
} else {
Toast.makeText(getApplicationContext(), "Error!!", Toast.LENGTH_LONG).show();
}
}

Error converting http entity result java.lang.NullPointerException: lock == null

I am new to develop an android application. I have read a lot of related post regarding the question I was asking but the tips or solution from the post did not solve my problem. (Looking for the solution for a week already, really need help in order to proceed with my project) Thanks a lot...
Error line No 121
Image LinK
update.java:
package pounkumarpurushothaman.ghssvmm;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;
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 java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class update extends ActionBarActivity {
public static final String KEY_121 ="http://ghssvmm.site40.net/update.php";
static Activity thisActivity = null;
InputStream is = null;
// LinearLayout yy=(LinearLayout)findViewById(R.id.uy);
// LinearLayout pp=(LinearLayout)findViewById(R.id.up);
//LinearLayout cc=(LinearLayout)findViewById(R.id.uc);
//LinearLayout ca=(LinearLayout)findViewById(R.id.uca);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
getServerData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_update, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void getServerData() {
thisActivity=this;
EditText f = (EditText) findViewById(R.id.ufst);
EditText l = (EditText) findViewById(R.id.ulst);
Spinner bld=(Spinner)findViewById(R.id.ubld);
Spinner stat=(Spinner)findViewById(R.id.ustatus);
Spinner bth=(Spinner)findViewById(R.id.ubat);
EditText dob = (EditText) findViewById(R.id.udob);
EditText phn1 = (EditText) findViewById(R.id.uphn);
EditText phn2 = (EditText) findViewById(R.id.uphn2);
EditText padd = (EditText) findViewById(R.id.upadd);
EditText radd = (EditText) findViewById(R.id.uradd);
EditText vill = (EditText) findViewById(R.id.uvill);
Spinner sec=(Spinner)findViewById(R.id.usec);
Spinner deg=(Spinner)findViewById(R.id.udeg);
EditText dept = (EditText) findViewById(R.id.udept);
EditText clg = (EditText) findViewById(R.id.uclg);
EditText yop = (EditText) findViewById(R.id.uyop);
EditText pos = (EditText) findViewById(R.id.upos);
EditText cmp = (EditText) findViewById(R.id.ucom);
EditText cadd = (EditText) findViewById(R.id.ucaddr);
String result = "";
//the year data to send
final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email","abc#gmail.com"));
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(thisActivity, "Error in http connection " + e.toString(),Toast.LENGTH_LONG).show();
}
}
});
thread.start();
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder 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(this, "Error converting result "+e.toString(),Toast.LENGTH_LONG).show();
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
f.setText(json_data.getString("fname"));
l.setText(json_data.getString("lname"));
dob.setText(json_data.getString("dob"));
switch(json_data.getString("blood")){
case "O Positive":
bld.setSelection(1);
break;
case "O Negative":
bld.setSelection(2);
break;
case "A Positive":
bld.setSelection(3);
break;
case "A Negative":
bld.setSelection(4);
break;
case "B Positive":
bld.setSelection(5);
break;
case "B Negative":
bld.setSelection(6);
break;
case "AB Positive":
bld.setSelection(7);
break;
case "AB Negative":
bld.setSelection(8);
break;
}
switch(json_data.getString("section")) {
case "A":
sec.setSelection(1);
break;
case "B":
sec.setSelection(2);
break;
case "C":
sec.setSelection(3);
break;
}
phn1.setText(json_data.getString("phn"));
phn2.setText(json_data.getString("phn2"));
padd.setText(json_data.getString("add"));
radd.setText(json_data.getString("add2"));
switch(json_data.getString("status")) {
case "Student":
stat.setSelection(1);
/* cc.setVisibility(View.INVISIBLE);
yy.setVisibility(View.INVISIBLE);
pp.setVisibility(View.INVISIBLE);
ca.setVisibility(View.INVISIBLE);*/
break;
case "Employee":
stat.setSelection(2);
/*cc.setVisibility(View.VISIBLE);
yy.setVisibility(View.VISIBLE);
pp.setVisibility(View.VISIBLE);
ca.setVisibility(View.VISIBLE);*/
break;
case "Un Employee":
stat.setSelection(3);
/* cc.setVisibility(View.INVISIBLE);
yy.setVisibility(View.VISIBLE);
pp.setVisibility(View.INVISIBLE);
ca.setVisibility(View.INVISIBLE);*/
break;
}
switch(json_data.getString("degree")) {
case "B.E":
deg.setSelection(1);
break;
case "Arts and Science":
deg.setSelection(2);
break;
case "Medical":
deg.setSelection(3);
break;
}
dept.setText(json_data.getString("dept"));
clg.setText(json_data.getString("clg"));
yop.setText(json_data.getString("yop"));
pos.setText(json_data.getString("pos"));
cmp.setText(json_data.getString("com"));
cadd.setText(json_data.getString("caddr"));
vill.setText(json_data.getString("vill"));
//Get an output to the screen
}
}catch(JSONException e) {
Toast.makeText(this, "Error parsing data " + e.toString(), Toast.LENGTH_LONG).show();
}
}
}
**
Logcat :
**
04-06 14:11:39.580 25919-25919/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: pounkumarpurushothaman.ghssvmm, PID: 25919
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{pounkumarpurushothaman.ghssvmm/pounkumarpurushothaman.ghssvmm.update}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2081)
at pounkumarpurushothaman.ghssvmm.update.<init>(update.java:34)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1572)
at android.app.Instrumentation.newActivity(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
.
Here's how you get response after your POST request is executed .
HttpResponse response = httpClient.execute(httpPost);
String op = EntityUtils.toString(response.getEntity(), "UTF-8");
Log.d("Response:", op);

I keep getting a nullpointer exception with my JSON Object Calls

For some reason I keep getting a nullpointer exception with my double parsing. AFter further inquiry there seems to be some issue with my JSON Objects but I have no clue what the issue is.I am pulling JSON data form openweathermap api. I scuessfully pulled and printed the data into the log.i, however when I try to access with the JSONObject I am getting an error. Please help.
Code:
package com.anuraagy.myweather;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.content.*;
import android.os.Build;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
public class MyActivity extends Activity {
private String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
private JSONObject myObject,mainObject,nameObject;
private ImageView myImage;
private TextView titleText;
private String hello,weatherName,max_temp,min_temp;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
RequestTask task = new RequestTask();
task.execute(new String[]{"http://api.openweathermap.org/data/2.5/weather?q=Ashburn&APPID=970bf0e4978dae293b065f8f2830ba58"});
return rootView;
}
public class RequestTask extends AsyncTask<String, String, String> {
private TextView myView;
private String s;
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
Log.i("", responseString);
return responseString;
}
#Override
protected void onPostExecute(String result){
Log.i("","hello");
super.onPostExecute(result);
try {
myObject = new JSONObject(result);
nameObject = myObject.getJSONObject("weather");
weatherName = nameObject.getString("main");
mainObject = myObject.getJSONObject("main");
Log.i("Wather Name",weatherName);
Log.i("mainObject",mainObject.toString());
hello = mainObject.getString("temp");
max_temp = mainObject.getString("temp_max");
min_temp = mainObject.getString("temp_min");
} catch(JSONException jsonException){
}
double f = Double.parseDouble(hello);
double max = Double.parseDouble(max_temp);
double min = Double.parseDouble(min_temp);
double realMax = (max - 273)* 1.8 + 32;
double realMin = (min - 273)* 1.8 + 32;
double realTemp = (max - 273)* 1.8 + 32;
int myMax = (int)realMax;
int myMin = (int)realMin;
int myWeather = (int)realTemp;
titleText = (TextView)getActivity().findViewById(R.id.textView3);
String fe = titleText.getText().toString();
fe.replace("definetly",weatherName);
myView = (TextView)getActivity().findViewById(R.id.textView);
// if()
// {
//
// }
// else
// {
//
// }
myImage = (ImageView)getActivity().findViewById(R.id.imageView);
myImage.setImageResource(R.drawable.clearnight);
String weather = myWeather + "";
myView.setText(weather + (char) 0x00B0 +"F");
// //Do anything with response..
}
}
}
}
Error:
10-16 10:01:26.398 664-664/com.anuraagy.myweather E/Trace﹕ error opening trace file: No such file or directory (2)
10-16 10:01:35.058 664-668/com.anuraagy.myweather D/dalvikvm﹕ GC_CONCURRENT freed 75K, 2% free 11112K/11335K, paused 17ms+3ms, total 312ms
10-16 10:01:35.058 664-664/com.anuraagy.myweather D/dalvikvm﹕ WAIT_FOR_CONCURRENT_GC blocked 282ms
10-16 10:01:35.498 664-664/com.anuraagy.myweather D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
10-16 10:01:38.388 664-680/com.anuraagy.myweather I/﹕ {"coord":{"lon":-77.49,"lat":39.04},"sys":{"type":1,"id":2856,"message":0.0194,"country":"US","sunrise":1413458470,"sunset":1413498574},"weather":[{"id":701,"main":"Mist","description":"mist","icon":"50d"},{"id":721,"main":"Haze","description":"haze","icon":"50d"},{"id":741,"main":"Fog","description":"fog","icon":"50d"}],"base":"cmc stations","main":{"temp":288.03,"pressure":1008,"humidity":100,"temp_min":286.15,"temp_max":290.15},"wind":{"speed":2.86,"deg":261.502},"clouds":{"all":90},"dt":1413468071,"id":4744870,"name":"Ashburn","cod":200}
10-16 10:01:38.398 664-664/com.anuraagy.myweather I/﹕ hello
10-16 10:01:38.438 664-664/com.anuraagy.myweather D/AndroidRuntime﹕ Shutting down VM
10-16 10:01:38.438 664-664/com.anuraagy.myweather W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40a13300)
10-16 10:01:38.448 664-664/com.anuraagy.myweather E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at java.lang.StringToReal.parseDouble(StringToReal.java:244)
at java.lang.Double.parseDouble(Double.java:295)
at com.anuraagy.myweather.MyActivity$PlaceholderFragment$RequestTask.onPostExecute(MyActivity.java:141)
at com.anuraagy.myweather.MyActivity$PlaceholderFragment$RequestTask.onPostExecute(MyActivity.java:91)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Be careful - "weather" is a JSONArray, not a JSONObject. The NullPointerException is likely due to that.
Try instead using myObject.getJSONArray("weather"), and from there iterate through the JSONObjects inside.
See here for more information on that last part: Accessing members of items in a JSONArray with Java
It looks like myObject doesn't have item named "temp", so:
- on line 133 you set hello to null
- on line 141 you pass that null to Double.parseDouble()
- get your exception because class Double can't digest null
That's it!
Check it in the debugger, but I'm almost sure - according to your stack trace

Android not sending mail

I am creating a application which gets the input from edit text and sends a mail acording to the information.I am using Http post to do this i want to communicate with the Php script to send the mail please have a look at my code..
Php script
<?php
$name = $_POST['name'];
$to = $_POST['to'];
$from = $_POST['from'];
$subject = $_POST['subject'];
$message = "From: ".$name."\r\n";
$message .= $_POST['message'];
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
?>
my Activity:
package dolphin.developers.com;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.protocol.HTTP;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import dolphin.devlopers.com.R;
public class misc1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.eamilspoof);
EditText textw =(EditText) findViewById(R.id.editText1);
final String strd = textw.getText().toString();
EditText textw3 =(EditText) findViewById(R.id.editText2);
final String strd3 = textw3.getText().toString();
EditText textw3d =(EditText) findViewById(R.id.editText3d);
final String strd3d = textw3d.getText().toString();
EditText textw3dd =(EditText) findViewById(R.id.editText3);
final String name = textw3d.getText().toString();
EditText textw3df =(EditText) findViewById(R.id.editText4);
final String subject = textw3d.getText().toString();
Button pds = (Button)findViewById(R.id.button1d);
pds.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String site = "www.dolphin123.net78.net/mailer.php";
String namer1 = name;
String to = strd;
String from = strd3;
String subject1 = subject;
String message = strd3d;
String content = "";
try
{
/* Sends data through a HTTP POST request */
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(site);
List <NameValuePair> params = new ArrayList <NameValuePair> ();
params.add(new BasicNameValuePair("name", namer1));
params.add(new BasicNameValuePair("to", to));
params.add(new BasicNameValuePair("from", from));
params.add(new BasicNameValuePair("subject", subject1));
params.add(new BasicNameValuePair("message", message));
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
/* Reads the server response */
HttpResponse response = httpClient.execute(httpPost);
InputStream in = response.getEntity().getContent();
StringBuffer sb = new StringBuffer();
int chr;
while ((chr = in.read()) != -1)
{
sb.append((char) chr);
}
content = sb.toString();
in.close();
/* If there is a response, display it */
if (!content.equals(""))
{
Log.i("HTTP Response", content);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
};
}
}
Logcat :
08-10 17:55:20.405: W/System.err(12988): java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=www.dolphin123.net78.net/mailer.php
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:591)
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293)
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
08-10 17:55:20.410: W/System.err(12988): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-10 17:55:20.410: W/System.err(12988): at dolphin.developers.com.misc1$1.onClick(misc1.java:87)
08-10 17:55:20.410: W/System.err(12988): at android.view.View.performClick(View.java:4211)
08-10 17:55:20.410: W/System.err(12988): at android.view.View$PerformClick.run(View.java:17267)
08-10 17:55:20.410: W/System.err(12988): at android.os.Handler.handleCallback(Handler.java:615)
08-10 17:55:20.410: W/System.err(12988): at android.os.Handler.dispatchMessage(Handler.java:92)
new Log:
08-05 13:08:17.365: D/SntpClient(73): request time failed: java.net.SocketException: Address family not supported by protocol
Prepend the protocol to the String representation of your URI.
So it should be: "http://www.dolphin123.net78.net/mailer.php"
You can your url with above url with prepend http://

Categories