You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从谷歌地图公开数据提取业务信息时遇NullPointerException求助

解决WebView网页抓取应用的NullPointerException错误

我正在开发一款基于WebView的网页抓取应用,用户输入特定数据搜索目标,但运行时出现错误,需要修复以正常运行。

错误信息

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.StringBuilder java.lang.StringBuilder.append(java.lang.String)' on a null object reference
at com.education.saifgroupgrabber.WebScraper.onCreate(WebScraper.java:225)

相关代码

LeadsExtractorActivity.Java

public class LeadsExtractorActivity extends BaseActivity {
public TextInputEditText j;
public TextInputEditText k;
public String l;
public String m;
public SharedPreferences n;

public void Captcha(View view) {
    startActivity(new Intent(this, GoogleCaptchaActivity.class));
}

public void StartExtractor(View view) {
    String obj = this.j.getText().toString();
    this.l = obj;
    String str = "";
    if (obj.equals(str)) {
        this.j.setError("Please Enter Business Keyword");
        return;
    }
    String obj2 = this.k.getText().toString();
    this.m = obj2;
    String str2 = "";
    if (obj2.equals(str2)) {
        this.k.setError("Please Enter Area / Location");
        return;
    }
    try {
        str = URLEncoder.encode(this.l, JsonRequest.PROTOCOL_CHARSET) + " in " + URLEncoder.encode(this.m, JsonRequest.PROTOCOL_CHARSET);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    SharedPreferences.Editor edit = this.n.edit();
    edit.putString(PreferencesConstants.SessionManager.GROUP_NAME, this.l + " in " + this.m);
    edit.commit();
    Intent intent = new Intent(this, WebScraper.class);
    intent.putExtra("SEARCH", str);
    startActivity(intent);
}

public void StartExtractorNew(View view) {
    String obj = this.j.getText().toString();
    this.l = obj;
    String str = "";
    if (obj.equals(str)) {
        this.j.setError("Please Enter Business Keyword");
        return;
    }
    String obj2 = this.k.getText().toString();
    this.m = obj2;
    if (obj2.equals(str)) {
        this.k.setError("Please Enter Area / Location");
        return;
    }
    try {
        str = URLEncoder.encode(this.l, JsonRequest.PROTOCOL_CHARSET) + " in " + URLEncoder.encode(this.m, JsonRequest.PROTOCOL_CHARSET);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    SharedPreferences.Editor edit = this.n.edit();
    edit.putString(PreferencesConstants.SessionManager.GROUP_NAME, this.l + " in " + this.m);
    edit.commit();
    Intent intent = new Intent(this, WebScraper.class);
    intent.putExtra("SEARCH", str);
    startActivity(intent);
}

public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView((int) R.layout.activity_leads_extractor);
    setTitle("BZ 2 BZ Leads Extractor");
    try {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    } catch (NullPointerException unused) {
        Log.e("SearchActivity Toolbar", "You have got a NULL POINTER EXCEPTION");
    }
    this.j = (TextInputEditText) findViewById(R.id.businesskeyword_edit_text);
    this.k = (TextInputEditText) findViewById(R.id.location_edit_text);
    this.n = getSharedPreferences(PreferencesConstants.APP_MAIN_PREF, 0);
}

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater();
    return super.onCreateOptionsMenu(menu);
}

public boolean onOptionsItemSelected(MenuItem menuItem) {
    if (menuItem.getItemId() != 16908332) {
        return super.onOptionsItemSelected(menuItem);
    }
    finish();
    return true;
}
}

WebScraper.Java

public class WebScraper extends AppCompatActivity {

public static ArrayList<LeadsNumbersListModel> contactsData = new ArrayList<>();
public WebView h;
public volatile boolean i = false;
public TextView j;
public TextView k;
public TextView l;
public String m = "";
public ArrayList<String> n = new ArrayList<>();
public int o = 0;
public SharedPreferences p;
public boolean q = true;
public String r = "";
public String s = "";
public String t = "";
public boolean u = true;
public String v = "";
public String w = "";
private PowerManager.WakeLock wl;
public int x = 0;
public boolean y = false;
public final Thread z = new Thread(new Runnable() {
    public void run() {
        while (!WebScraper.this.i) {
            for (int i = 0; i < 20 && !WebScraper.this.i; i++) {
                int finalI = i;
                WebScraper.this.h.post(new Runnable() {
                    public void run() {
                        try {
                            WebScraper.this.h.loadUrl(ChromeHelper.HeaderClick(finalI));
                        } catch (Exception unused) {
                        }
                    }
                });
                WebScraper webScraper = WebScraper.this;
                if (webScraper.y) {
                    webScraper.y = false;
                    try {
                        Thread.sleep(5500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    Thread.sleep(5500);
                } catch (InterruptedException e2) {
                    e2.printStackTrace();
                }
                WebScraper.this.runOnUiThread(new Runnable() {
                    public void run() {
                        WebScraper.this.process44();
                    }
                });
                if (i >= 19) {
                    WebScraper.this.h.post(new Runnable() {
                        public void run() {
                            try {
                                WebScraper.this.h.loadUrl(ChromeHelper.NextClicker);
                                WebScraper.this.h.clearCache(true);
                            } catch (Exception unused) {
                            }
                        }
                    });
                    try {
                        Thread.sleep(4000);
                    } catch (InterruptedException e3) {
                        e3.printStackTrace();
                    }
                    WebScraper.this.h.post(new Runnable() {
                        public void run() {
                            try {
                                WebScraper webScraper = WebScraper.this;
                                webScraper.w = webScraper.h.getUrl();
                            } catch (Exception unused) {
                            }
                        }
                    });
                }
            }
        }
        WebScraper.deleteCache(WebScraper.this.getApplicationContext());
        WebScraper.this.startActivity(new Intent(WebScraper.this, LeadsContactsActivity.class));
        WebScraper.this.finish();
    }
});

public class MyWebViewClient extends WebViewClient {
    private int running = 0;

    public MyWebViewClient() {
    }

    public void onPageFinished(WebView webView, String str) {
        int i = this.running - 1;
        this.running = i;
        if (i == 0) {
            WebScraper webScraper = WebScraper.this;
            if (webScraper.q) {
                webScraper.q = false;
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        WebScraper.this.z.start();
                    }
                }, 1000);
                WebScraper.this.j.setText("Extracting Leads...");
            }
        }
    }

    public void onPageStarted(WebView webView, String str, Bitmap bitmap) {
        this.running = Math.max(this.running, 1);
    }

    public boolean shouldOverrideUrlLoading(WebView webView, String str) {
        this.running++;
        if (!str.startsWith("source://")) {
            return false;
        }
        try {
            WebScraper.this.sourceReceived(URLDecoder.decode(str, "UTF-8").substring(9));
        } catch (UnsupportedEncodingException unused) {
        }
        return true;
    }
}

public static void deleteCache(Context context) {
    try {
        deleteDir(context.getCacheDir());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static boolean deleteDir(File file) {
    if (file != null && file.isDirectory()) {
        for (String file2 : file.list()) {
            if (!deleteDir(new File(file, file2))) {
                return false;
            }
        }
        return file.delete();
    } else if (file == null || !file.isFile()) {
        return false;
    } else {
        return file.delete();
    }
}

public void PremiumPlan() {
    new AlertDialog.Builder(this).setTitle((CharSequence) "Premium Feature").setMessage((CharSequence) "You can extract only five leads in Trial Plan for unlimited leads please purchase premium").setCancelable(false).setPositiveButton((CharSequence) "OK", (DialogInterface.OnClickListener) new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialogInterface, int i) {
            WebScraper.this.i = true;
            WebScraper.this.k.setText("Stopping Please Wait...");
            WebScraper webScraper = WebScraper.this;
            webScraper.k.setTextColor(webScraper.getResources().getColor(R.color.main_red));
            WebScraper.this.l.setText("");
        }
    }).show();
}

public void onBackPressed() {
    super.onBackPressed();
}

public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    this.wl = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(26, "FASTY:SCREEN_LOCK");
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        this.m = extras.getString("SEARCH");
    }
    setContentView((int) R.layout.activity_web_scraper);
    contactsData.clear();
    setTitle("B2B Leads Extractor");
    try {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    } catch (NullPointerException unused) {
        Log.e("SearchActivity Toolbar", "You have got a NULL POINTER EXCEPTION");
    }
    this.p = getSharedPreferences(PreferencesConstants.APP_MAIN_PREF, 0);
    this.j = (TextView) findViewById(R.id.progressTV);
    this.k = (TextView) findViewById(R.id.tv);
    this.l = (TextView) findViewById(R.id.tv2);
    WebView webView = (WebView) findViewById(R.id.wv);
    this.h = webView;
    webView.getSettings().setJavaScriptEnabled(true);
    this.h.getSettings().setBuiltInZoomControls(false);
    this.h.getSettings().setSupportZoom(true);
    this.h.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
    this.h.setWebViewClient(new MyWebViewClient());
    this.h.setWebChromeClient(new WebChromeClient() {
    });
    this.h.getSettings().setUserAgentString("Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36");
    WebView webView2 = this.h;
    StringBuilder u2 = this.u("https://www.google.com/search?tbm=lcl&q=");
    u2.append(this.m);
    webView2.loadUrl(u2.toString());
    this.v = "https://www.google.com/search?tbm=lcl&q=" + this.m;
    this.j.setText("Please Wait\nLoading Search...");
    this.wl.acquire();
}

private StringBuilder u(String s) {
    return null;
}

public void onDestroy() {
    super.onDestroy();
    this.wl.release();
}

public void process44() {
    try {
        viewSource();
    } catch (Exception e) {
        Toast.makeText(this, "Error:" + e, Toast.LENGTH_LONG).show();
    }
     }
}

解决方案

问题根源

错误出在WebScraper类的onCreate方法中,调用u()方法后得到了null对象,接着尝试调用该对象的append()方法,触发空指针异常。查看u()方法的实现,它直接返回null,没有创建有效的StringBuilder实例。

修复代码

修改WebScraper类中的u()方法,让它返回一个初始化好的StringBuilder,将传入的字符串作为初始内容:

private StringBuilder u(String s) {
    return new StringBuilder(s);
}

修改后,调用u("https://www.google.com/search?tbm=lcl&q=")会返回一个包含该URL前缀的StringBuilder对象,后续调用append(this.m)就能正常拼接搜索参数,避免空指针异常。

内容的提问来源于stack exchange,提问作者Maria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 18:14:50