dougong9987 2018-04-22 00:14
浏览 54
已采纳

通过php发送网络请求时,活动崩溃

Good day to all.

I'm creating a social android app for posting offers of services for the skilled & talented within our univerity. I'm using the conventional languages for android: Java and XML.

But whenever I invoke the createOffer method within the CreateOfferActivity the app crashes without producing any exceptions and simply restarts.

Here's the code for CreateOfferActivity:

package com.italent.italent;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class CreateOfferActivity extends AppCompatActivity {

private EditText offerTitle;
private EditText offerDesc;
private EditText offerMinPrice;
private EditText offerMaxPrice;

private Spinner offerCategory;

private Button crtOffer;

String offCategory;
String imagePath;

public double minPrice;
public double maxPrice;

private static final String TAG = "CreateOfferActivity";
private static final String URL_FOR_CREATING_OFFER = "https://*****/create_offer.php";
ProgressDialog progressDialog;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create_offer);

    offerTitle = (EditText) findViewById(R.id.etOfferTitle);
    offerDesc = (EditText) findViewById(R.id.etOfferDesc);
    offerMinPrice = (EditText) findViewById(R.id.etMinPrice);
    offerMaxPrice = (EditText) findViewById(R.id.etMaxPrice);

    offerCategory = (Spinner) findViewById(R.id.spCategories);

    crtOffer = (Button) findViewById(R.id.bCreateOffer);


    ArrayAdapter<CharSequence> arrAdapter = ArrayAdapter.createFromResource(this,
            R.array.category_Array, android.R.layout.simple_spinner_item);

    // Specify the layout to use when the list of choices appears
    arrAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // Apply the adapter to the spinner
    offerCategory.setAdapter(arrAdapter);

    //Create Offer button onClick listener
    crtOffer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            submitOfferForm();
            Toast.makeText(CreateOfferActivity.this, "It works...", Toast.LENGTH_LONG).show();
        }
    });

}

private void submitOfferForm() {

    String offTitle = offerTitle.getText().toString();
    String offDesc = offerDesc.getText().toString();

    //////////Replace image path later with a valid one
    imagePath = "Some Image Path";


    offCategory = offerCategory.getSelectedItem().toString();

    //getting sharedPreferences file named userInfo to retrieve MemberName, Username and branch
    SharedPreferences sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
    String ofMName = sharedPreferences.getString("MemberName:", "");
    String ofUName = sharedPreferences.getString("UserName:", "");
    String ofBranch = sharedPreferences.getString("Branch:", "");

    String mnPri = " " + minPrice;
    String mxPri = " " + maxPrice;

    createOffer(ofMName, ofUName, offTitle, offDesc, ofBranch, mnPri, mxPri, imagePath, offCategory);
}


private void createOffer(final String oMName, final String oUName,  final String oTitle, final String oText,
                          final String oBranch,final String oMinPri, final String oMaxPri, final String oImage, final String oCategory) {
    // Tag used to cancel the request
    String cancel_req_tag = "offer";

    progressDialog.setMessage("Adding your offer...");
    showDialog();

    StringRequest strReq = new StringRequest(Request.Method.POST,
            URL_FOR_CREATING_OFFER, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Offer Response: " + response.toString());
            hideDialog();

            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");

                if (!error) { // error is set to false, meaning no error
                    //String user = jObj.getJSONObject("offer").getString("name");
                    Toast.makeText(CreateOfferActivity.this, "Your Offer has been created!", Toast.LENGTH_SHORT).show();

                    // Launch Home activity
                    Intent HomeIntent = new Intent(CreateOfferActivity.this, HomeActivity.class);
                    startActivity(HomeIntent);
                    finish();
                } else {

                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(CreateOfferActivity.this, errorMsg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Error in creating offer: " + error.getMessage());
            Toast.makeText(CreateOfferActivity.this,
                    error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            // Posting params to create offer url
            Map<String, String> params = new HashMap<String, String>();

            params.put("offerMemberName", oMName);
            params.put("offerUserName", oUName);
            params.put("offerTitle", oTitle);
            params.put("OfferText", oText);
            params.put("OfferBranch", oBranch);
            params.put("OfferDateTime", DateFormat.getDateTimeInstance().format(new Date()));
            params.put("OfferMinPrice", "" + oMinPri);
            params.put("OfferMaxPrice", "" + oMaxPri);
            params.put("OfferCategory", oCategory);
            params.put("OfferImage", oImage);

            return params;
        }
    };

    // Adding request to request queue
    AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}

private void showDialog() {
    if (!progressDialog.isShowing())
        progressDialog.show();
}

private void hideDialog() {
    if (progressDialog.isShowing())
        progressDialog.dismiss();
}
}

And the code for create_offer.php

<?php

require_once 'update_user_info.php';
$db = new update_user_info();

// json response array
$response = array("error" => FALSE);

if (isset($_POST['offerTitle']) && isset($_POST['offerMname']) &&         isset($_POST['offerBranch']) && isset($_POST['offerText']) && isset($_POST['offerImageURL']) && 
isset($_POST['offerDateTime']) && isset($_POST['offerMinPrice']) && isset($_POST['offerMaxPrice']) && isset($_POST['offerCategory']) && isset($_POST['offerUname'])) {

// receiving the post params
$ofTitle = $_POST['offerTitle'];
$ofMName = $_POST['offerMname'];
$ofBranch = $_POST['offerBranch'];
$ofText = $_POST['offerText'];
$ofImageURL = $_POST['offerImageURL'];
$ofDateTime = $_POST['offerDateTime'];
$ofMinPri = $_POST['offerMinPrice'];
$ofMaxPri = $_POST['offerMaxPrice'];
$ofCategory = $_POST['offerCategory'];
$ofUName = $_POST['offerUname'];


// check if user is already existed with the same email
if (!($db->checkExistingUserThruUname($ofUName))) {
    // user doesn't exist
    $response["error"] = TRUE;
    $response["error_msg"] = "Visitors cannot post an offer. Please register first.";
    echo json_encode($response);
} else {
    // create a new offer 
    $user = $db->storeOfferInfo($ofTitle, $ofMName, $ofBranch, $ofText, $ofImageURL, $ofDateTime, $ofMinPri, $ofMaxPri, $ofCategory, $ofUName);
    if ($offer) {
        // offer stored successfully
        $response["error"] = FALSE;
        $response["offer"]["offTitle"] = $offer["offTitle"];
        $response["offer"]["offMname"] = $offer["offMname"];
        $response["offer"]["offBranch"] = $offer["offBranch"];
        $response["offer"]["offText"] = $offer["offText"];
        $response["offer"]["offImageURL"] = $offer["offImageURL"];
        $response["offer"]["offDateTime"] = $offer["offDateTime"];
        $response["offer"]["offMinPrice"] = $offer["offMinPrice"];
        $response["offer"]["offMaxPrice"] = $offer["offMaxPrice"];
        $response["offer"]["offCategory"] = $offer["offCategory"];
        $response["offer"]["offUname"] = $offer["offUname"];

        echo json_encode($response);
    } else {
        // offer failed to store
        $response["error"] = TRUE; 
        $response["error_msg"] = "Unknown error occurred in offer creation!";
        echo json_encode($response);
    }
 }
} else {
$response["error"] = TRUE;
$response["error_msg"] = "A required field is missing!";
echo json_encode($response);
}
?>

This is the Logcat:

04-22 03:24:38.950 27998-27998/com.italent.italent E/AndroidRuntime: FATAL EXCEPTION: main
                                                                 Process: com.italent.italent, PID: 27998
                                                                 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ProgressDialog.setMessage(java.lang.CharSequence)' on a null object reference
                                                                     at com.italent.italent.CreateOfferActivity.createOffer(CreateOfferActivity.java:122)
                                                                     at com.italent.italent.CreateOfferActivity.submitOfferForm(CreateOfferActivity.java:113)
                                                                     at com.italent.italent.CreateOfferActivity.access$000(CreateOfferActivity.java:30)
                                                                     at com.italent.italent.CreateOfferActivity$1.onClick(CreateOfferActivity.java:86)
                                                                     at android.view.View.performClick(View.java:5697)
                                                                     at android.widget.TextView.performClick(TextView.java:10826)
                                                                     at android.view.View$PerformClick.run(View.java:22526)
                                                                     at android.os.Handler.handleCallback(Handler.java:739)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                     at android.os.Looper.loop(Looper.java:158)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:7225)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

P.S. i used almost the exact same java code, php code and database for registration and it works fine but i can't find why it doesn't work with this class.

I appreciate any guidlines or help. Thank you!

  • 写回答

1条回答 默认 最新

  • dqp99585 2018-04-22 00:35
    关注

    progressDialog variable is not initialized. Add following code in your activity onCreate()

     ProgressDialog progressDialog = new ProgressDialog(this);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序