Попытка подключить Android Studio к базе данных MySQL через переполнение стека

У меня есть простая форма, которая при заполнении должна вставить данные в базу данных (localhost) с помощью php.
Когда я нажимаю на кнопку, он говорит, что имя приложения, к сожалению, перестало работать.

Вот мой код

Основной класс Java

public class MainActivity extends ActionBarActivity {JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;

// url to create new product
private static String url_create_product = "http://localhost/create_product.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);

// Create button
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);

// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}

/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {

/**
* Before starting background thread Show Progress Dialog
* *//**
* Creating product
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();

// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));

// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);

// check log cat fro response
Log.d("Create Response", json.toString());

// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);

if (success == 1) {finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}

return null;
}}

JSONParser Class

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {

// Making HTTP request
try {

// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}

Основная деятельность (содержит форму)

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" >

<!-- Name Label -->
<TextView android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Name"android:paddingLeft="10dip"android:paddingRight="10dip"android:paddingTop="10dip"android:textSize="17dip"/>

<!-- Input Name -->
<EditText android:id="@+id/inputName"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_margin="5dip"android:layout_marginBottom="15dip"android:singleLine="true"/>

<!-- Price Label -->
<TextView android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Age"android:paddingLeft="10dip"android:paddingRight="10dip"android:paddingTop="10dip"android:textSize="17dip"/>

<!-- Input Price -->
<EditText android:id="@+id/inputPrice"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_margin="5dip"android:layout_marginBottom="15dip"android:singleLine="true"android:inputType="numberDecimal"/>

<!-- Description Label -->
<TextView android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Email"android:paddingLeft="10dip"android:paddingRight="10dip"android:paddingTop="10dip"android:textSize="17dip"/>

<!-- Input description -->
<EditText android:id="@+id/inputDesc"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_margin="5dip"android:layout_marginBottom="15dip"android:lines="4"android:gravity="top"/>

<!-- Button Create Product -->
<Button android:id="@+id/btnCreateProduct"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Sign Up"/>

</LinearLayout>

Мой манифест

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="cambiopune.onlinedatabase" >

<uses-permission android:name="android.permission.INTERNET" />

<application
android:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<activity android:name=".JSONParser" />
</activity>

</application>

</manifest>

Ошибка журнала, которую я получаю при нажатии кнопки

 03-31 11:04:19.290  20660-20696/cambiopune.onlinedatabase E/Buffer Error﹕             Error converting result java.lang.NullPointerException: lock == null

03-31 11:04:19.290  20660-20696/cambiopune.onlinedatabase E/JSON Parser﹕   Error parsing data org.json.JSONException: End of input at character 0 of

03-31 11:04:19.297  20660-20696/cambiopune.onlinedatabase E/AndroidRuntime﹕`    enter code here` FATAL EXCEPTION: AsyncTask #5
Process: cambiopune.onlinedatabase, PID: 20660
java.lang.RuntimeException: An error occured while executing             doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at                cambiopune.onlinedatabase.MainActivity$CreateNewProduct.doInBackground(MainActivity.java:106)
at cambiopune.onlinedatabase.MainActivity$CreateNewProduct.doInBackground(MainActivity.java:79)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at          java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at          java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)

-1

Решение

Вот ,

json = sb.toString();

Убедитесь, что ваш объект sb не нулевой.

0

Другие решения

Поэтому вы, вероятно, должны заметить, что «localhost» — это имя устройства, на котором запущен скрипт или веб-сервер. Если вы скажете «localhost» на вашем Android-устройстве, оно, вероятно, попытается найти сервер, работающий на вашем Android-устройстве.

Если на вашем компьютере запущен веб-сервер, то ваша сеть назначит IP-адрес этому компьютеру. Посмотрите на настройки вашей сети, а затем скажите вашему приложению Android, какой адрес … вместо «localhost»

Кроме того, если вы используете DHCP в своей сети, ваш компьютер (и, возможно, ваш телефон) будет переназначен. Если ваш компьютер получает новый IP-адрес, ничего не будет работать.

Кроме того, если ваш телефон использует WiFi в той же сети, у вас все в порядке. Если вы переключитесь на 4G или другую сеть WiFi, это, вероятно, не будет работать. Нет таблицы маршрутизации для обработки запросов.

0